<?php

namespace app\admin\controller;

use app\admin\model\ProjectYearSwitch;
use app\common\controller\Backend;
use app\admin\model\Fields;
use app\admin\model\Admin;
use app\admin\model\AdminProject;
use think\Db;
use fast\Random;
use app\admin\library\Time;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Projectbase extends Backend
{

    /**
     * Project模型对象
     * @var \app\admin\model\Project
     */
    protected $noNeedLogin = ['test'];
    protected $model = null;
    protected $fiveindustryArr = [];
    protected $streetArr = [];
    protected $industryCategoryArr = [];
    protected $tablename = 'project';
    protected $year;
    protected $chargedep_data = null;
    protected $pre = '';
    protected $project_socialized = [];
    protected $fields_tablename = 'project';
    protected $project_tablename = 'nsig_project_2020';
    protected $exportpre = '';
    public function _initialize()
    {

        parent::_initialize();

        // $this->year = date('Y');
        // $this->assign('year',$this->year);
        $this -> dispatchmodel = new \app\admin\model\Dispatch;

        // $this->relationtTable = 'managers';
        $this->fiveindustryArr = \app\admin\model\FiveIndustry::column('id,name');
        // $this->streetArr = \app\admin\model\Street::column('id,name');
        $this->industryCategoryArr = \app\admin\model\IndustryCategory::column('id,name');
        // $this->tablename = 'project';

        $groupIds = $this->auth->getGroupIds();
        $this->assignconfig('isSuperAdmin',$this->auth->isSuperAdmin());
        $this->assign('isSuperAdmin',$this->auth->isSuperAdmin());

        if(in_array(GROUP_BUSINESS,$groupIds) || in_array(GROUP_DISTRICTUNIT,$groupIds)){
            $this->assignconfig('isBuDi',true);
            $this->assign('isBuDi',true);
        }else{
            $this->assignconfig('isBuDi',false);
            $this->assign('isBuDi',false);
        }

        // 图标，管理员，街道，领导，双招双引才可查看
        $this->assignconfig('groupIds',$groupIds);



        $this->assignconfig('uid',$this->auth->id);
        $this -> assign('year',$this -> year);
        $this->chargedep_data = $this->auth->getChargedep();

        if($this->chargedep_data)
        {
            $chargedep_id = $this->chargedep_data->chargedep_id;
            $this->assignconfig('isbinddep',1);
        }
        else
        {
            $chargedep_id = 0;
            $this->assignconfig('isbinddep',0);
        }

        $this->assignconfig('chargedep_id',$chargedep_id);
        if($this->auth->isSuperAdmin())
            $this->pre = '';
        else
            $this->pre = 'tmp_';
        $this->assign('pre',$this->pre);
        $this->assignconfig('pre',$this->pre);
        $this->project_socialized = [
            ['item_id'=>'referrer','item_type'=>'string','item_label'=>'引荐人'],
            ['item_id'=>'first_registration_time','item_type'=>'date','item_label'=>'初次备案'],
            ['item_id'=>'first_registration_images','item_type'=>'upload','item_label'=>'初次备案附件'],
            ['item_id'=>'second_registration_time','item_type'=>'date','item_label'=>'二次备案'],
            ['item_id'=>'second_registration_images','item_type'=>'upload','item_label'=>'二次备案附件'],
            ['item_id'=>'final_confirm_time','item_type'=>'date','item_label'=>'最终确认'],
            ['item_id'=>'final_confirm_images','item_type'=>'upload','item_label'=>'最终确认附件'],
            ['item_id'=>'reward_application_time','item_type'=>'date','item_label'=>'奖励申请'],
            ['item_id'=>'reward_application_images','item_type'=>'upload','item_label'=>'奖励申请附件']
        ];
        $this->whereExtend['is_delete'] = 0;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    //在谈库
    public function discuss() {
        $where_str = '';
        $this->whereExtend['library_id'] = DISCUSS;
        $groupIds = $this->auth->getGroupIds();
        $showAna = true;
        if(/*in_array(GROUP_DISTRICTUNIT,$groupIds) || */in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }
        if(in_array(GROUP_DISTRICTUNIT,$groupIds) || in_array(GROUP_BUSINESS,$groupIds))//GROUP_BUSINESS 双招双引权限
        {
            // $this->whereExtend['is_add'] = 1;
            $this->whereExtend['is_visible'] = 1;
        }



        $nan = $this -> model -> query("select count(*) as 'projectcount',
sum(case library_id when 2 then 1 else 0 end ) as 'signedcount',
sum(case library_id when 1 then 1 else 0 end ) as 'discusscount',
sum(IF(investment_total > 0,investment_total,0)) as 'investment_total'
from ".$this->project_tablename." where library_id = 1 and is_visible = 1 and is_delete = 0 and suspend_type =0");
        $nan = $nan[0];
//        pr($nan);
        $str = <<<EOS
        全区在谈项目{$nan['discusscount']}个，计划总投资{$nan['investment_total']}亿元。<br />

EOS;

        $this -> assign('showana',$showAna);
        $this -> assign('str',$str);
        // if(in_array(GROUP_SOE,$groupIds) || in_array(GROUP_STREET,$groupIds) || in_array(GROUP_DISTRICTUNIT,$groupIds))
        // {
        //     $chargedep_data = $this->auth->getChargedep();
        //     if($chargedep_data){
        //         $chargedep_id = $chargedep_data->chargedep_id;
        //         // echo $chargedep_id;
        //         $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
        //         $this->assignconfig('chargedep_id',$chargedep_id);
        //     }
        //         // $this->whereExtend[] = '1 < 1';
        // }


        $this->assignconfig(('library_id'),DISCUSS);
        $this->assignconfig('is_important',0);

        $this->assignconfig(('library_id'),DISCUSS);
        $this->assignconfig('year',$this->year);

        return self::__baselist();
    }
    public function signed() {
        $this->whereExtend['library_id'] = SIGNED;
        $this->whereExtend['investment_total|tmp_investment_total'] = ['>=', 1];
        // $import_activity = (new Activity)->where(['is_important'=>1])->column('id');
        // $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($project_source_ids,import_activity)")];
        // $this->whereExtend['']
        // $this->whereExtend['is_important'] = 0;
        $groupIds = $this->auth->getGroupIds();

        $showAna = true;
        if(/*in_array(GROUP_DISTRICTUNIT,$groupIds) || */in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }
        if(in_array(GROUP_DISTRICTUNIT,$groupIds) )//GROUP_BUSINESS 双招双引权限
        {
            // $this->whereExtend['is_add'] = 1;
            $this->whereExtend['is_visible'] = 1;
        }
        $where_str = '';
        if(in_array(GROUP_BUSINESS,$groupIds) )
        {
            // $this->whereExtend['is_add'] = 1;
            $this->whereExtend['is_visible'] = 1;
            $this->whereExtend['is_visible_sz'] = 1;
            $where_str .= ' and is_visible_sz = 1';
        }
        // $where = ['library_id'=>SIGNED];
        $str = '';
        $str1 = '';
        $str = $this->anaData($where_str." and year = ".$this->year);
        if($this->year == 2021)
        {

            $str1 = $this->anaData($where_str." and year = 2020");

        }
        $this -> assign('showana',$showAna);
        $this -> assign('str',$str);
        $this -> assign('str1',$str1);

        $this->assignconfig('library_id',SIGNED);
        $this->assignconfig('is_important',0);
        $this->assignconfig('year',$this->year);
        return self::__baselist();
    }

    public function major() {
        $this->whereExtend['library_id'] = SIGNED;
        $this->whereExtend['is_important'] = 1;
        $this->whereExtend['year'] = $this->year;



        // $this->whereExtend['project_source_ids']= ['in','4,5,7,8,9,10,11,15,16,171,181,19,22,24,25,28,29,30,33,34,35,36,37,38,39'];
        // $this->whereExtend[] = ['investment_total','exp','not null'];

        $groupIds = $this->auth->getGroupIds();
        $showAna = true;
        if(/*in_array(GROUP_DISTRICTUNIT,$groupIds) || */in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }
        // $where = ['library_id'=>SIGNED];

        // var_dump($this->whereExtend);
        // exit();

        $this->assignconfig('library_id',SIGNED);
        $this->assignconfig('is_important',1);
        $this->assignconfig('year',$this->year);

        return self::__baselist();
    }

    /**
     * 新征地
     * @Author   ysq
     * @DateTime 2021-01-22
     * @return   [type]     [description]
     */
    public function new() {
        $this->whereExtend['carrier_id'] = 1;
        $this->whereExtend['is_visible'] = 1;
        $groupIds = $this->auth->getGroupIds();
        $showAna = true;
        if(/*in_array(GROUP_DISTRICTUNIT,$groupIds) || */in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }


        $this->assignconfig('library_id',6); //单独配置载体情况  盘活低效用地
        $this->assignconfig('year',$this->year);
        return self::__baselist();
    }



    public function bymonth() {
        $this->whereExtend['library_id'] = DISCUSS;
        $this->whereExtend['sign_time'] =  ['between', Time::month()];
        $this->assignconfig('library_id',DISCUSS);
        return self::__baselist();
    }

    public function activity(){
        $source_id = input('ids');
        // $value = Db::raw("FIND_IN_SET($source_id,project_source_ids)");
        $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($source_id,project_source_ids)")];
        // pr($where);
        $this->assignconfig('ids',$source_id);
        return self::__baselist();
    }

    public function discuss_add() {
        return self::__add(DISCUSS);
    }
    public function signed_add()
    {
        return self::__add(SIGNED);
    }

    public function major_add()
    {
        return self::__add(SIGNED,1);
    }


    public function edit($ids = NULL) {

        if(!$this->auth->isSuperAdmin())
        {
            $chargedep_data = $this->auth->getChargedep();

            if(!$chargedep_data)
                $this->error('您还未绑定部门或街道');

            $chargedep_id = $chargedep_data->chargedep_id;
            $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
        }

        $row = $this->model->get($ids);
        // $row = $this->model->where('id',$ids)->where($this->whereExtend)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->status == -1)
            $this->redirect('initedit', ['ids' => $ids]);

        $library_id = $row['library_id'];
        $field_where = $this->fieldWhere($library_id, ACTION_EDIT);
        $fields_list = Fields::where($field_where)->order('weight','asc')->select();

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        //处理年度
        // $years = [];
        // for ($i = config('app.start_year');$i <= date('Y') +1;$i++){
        //     $years[] = $i;
        // }


        // //查看project_year表中有没有该年度的记录，如果没有则插入
        // $projectYear = \app\admin\model\ProjectYear::get(['pno'=>$row->pno,'year'=>$this -> year]);
        // if(!$projectYear){
        //     (new \app\admin\model\ProjectYear()) -> insert(['pno'=>$row->pno,'year'=>$this -> year]);
        // }

        // $pYears = (new \app\admin\model\ProjectYear()) -> where('pno',$row -> pno)
        //     -> where('year','<=',date('Y'))
        //     -> column('year');

        // $this -> assign('pYears',implode(',',$pYears));
        // $this -> assign('years',$years);

        if ($this->request->isPost()) {
            $data = [];
            $params = $this->request->post("row/a");
            // pr($params);
            if ($params) {
                $params = $this->preExcludeFields($params);
                if(isset($params['memo']) && $params['memo'])
                    $data['memo'] = $params['memo'];
                if(isset($params['sort']) && $params['sort'])
                    $data['sort'] = $params['sort'];
                $field = $this->request->post("item_id");
                $field_row = Fields::where(['table_name'=>$this->fields_tablename, 'item_id'=>$field])->find();
                if($field_row){
                    if($params['value'] == PENDING_TEXT)
                        $params['value'] = PENDING;
                    $field_name = str_replace('id','name', $field);

                    $params_field = $this->auth->isSuperAdmin() ? $field :'tmp_'.$field;
                    $params_field_name = str_replace('id','name', $params_field);
                    $log_data = [];
                    $relation_log_data = [];

                    if(isset($params['status'])){
                        $data[$params_field.'_status'] = $params['status'];
                        $log_data['status'] = $params['status'];
                    }
                    $log_data['original_value'] = $row[$field] == PENDING ? PENDING_TEXT : $row[$field];
                    $log_data['value'] = $params['value'] == PENDING ? PENDING_TEXT : $params['value'];

                    $log_data['label'] = $field_row['item_label'];
                    $log_data['info'] = $params['desc_value'];  //

                    $data[$params_field.'_submit_desc'] = $params['desc_value'];

                    $data[$params_field] = $params['value'];

                    if($field_row['item_type'] == "select" || $field_row['item_type'] == "selects")
                    {
                        $data[$params_field] = is_array($params['value'])?implode(",",$params['value']):$params['value'];
                        $rule = json_decode($field_row['item_rule'], true);
                        if(is_string($rule['datasource'])){
                            $tb_name = $rule['datasource'];
                            $data[$params_field_name] =  getSelectText($tb_name,$params['value']);
                        }else
                            $data[$params_field_name] = $rule['datasource'][$params['value']];

                        $log_data['original_value'] = $row[$field_name];
                        $log_data['value'] = $data[$params_field_name];
                    }

                    if($field_row['item_type'] == "datetime" || $field_row['item_type'] == "date")
                    {
                        $log_data['original_value'] = $row[$field.'_desc'];
                        $log_data['value'] = $params['value'] == PENDING ? PENDING_TEXT : $params['value'];
                        if($params['value'] == PENDING)
                        {
                            $data[$params_field.'_desc'] = PENDING_TEXT;
                        }
                        else
                        {
                            $data[$params_field.'_desc'] = $params['value'];
                        }
                    }

                    // if($field_row['item_type'] == "radio"){
                    //     $log_data['original_value'] = $row[$field]? '是':'否';
                    //     $log_data['value'] = $params['value']? '是':'否';
                    // }

                    if($field == "carrier_id")
                    {
                        if($data[$params_field] != '5')
                        {
                            $data[$params_field.'_relation'] = $params['value_relation'];
                            $relation_log_data = $log_data;
                            $relation_log_data['label'] = '载体面积';
                            $relation_log_data['original_value'] = $row[$field."_relation"];
                            $relation_log_data['value'] = $params['value_relation'];
                        }
                    }

                    // if($field == "is_access") {
                    //     // 选项是
                    //     if ($data[$params_field] == '是') {
                    //         $data[$this->pre.'access_time'] = $params['relation_value'];
                    //         $data[$this->pre.'access_time_desc'] = $params['relation_value'];
                    //         $data[$this->pre.'access_time_status'] = $params['status'];
                    //         $relation_desc_value = (isset($params['relation_desc_value']) && $params['relation_desc_value'])?$params['relation_desc_value']:$params['desc_value'];
                    //         $data[$this->pre.'access_time_submit_desc'] = $relation_desc_value;


                    //         $relation_log_data['info'] = $relation_desc_value;  //
                    //         $relation_log_data['label'] = '准入时间';
                    //         // $relation_log_data[''] = '准入时间';
                    //         $relation_log_data['original_value'] = $row[$this->pre.'access_time'];
                    //         $relation_log_data['value'] = $params['relation_value'];
                    //         $relation_log_data['status'] = STATUS_SUBMIT;
                    //     }
                    //     // 选项无
                    //     if ($data[$params_field] == '无') {
                    //         $data[$this->pre.'access_remarks'] = $params['relation_value'];
                    //         $data[$this->pre.'access_remarks_desc'] = $params['relation_value'];
                    //         $data[$this->pre.'access_remarks_status'] = $params['status'];
                    //         $relation_desc_value = (isset($params['relation_desc_value']) && $params['relation_desc_value'])?$params['relation_desc_value']:$params['desc_value'];
                    //         $data[$this->pre.'access_remarks_submit_desc'] = $relation_desc_value;


                    //         $relation_log_data['info'] = $relation_desc_value;  //
                    //         $relation_log_data['label'] = '无须上准入例会备注';
                    //         // $relation_log_data[''] = '准入时间';
                    //         $relation_log_data['original_value'] = $row[$this->pre.'access_time'];
                    //         $relation_log_data['value'] = $params['relation_value'];
                    //         $relation_log_data['status'] = STATUS_SUBMIT;
                    //     }

                    // }
                    if($field == "is_land" && $data[$params_field] == '是') {
                        $data[$this->pre.'land_time'] = $params['relation_value'];
                        $data[$this->pre.'land_time_desc'] = $params['relation_value'];
                        $data[$this->pre.'land_time_status'] = $params['status'];
                        $relation_desc_value = (isset($params['relation_desc_value']) && $params['relation_desc_value'])?$params['relation_desc_value']:$params['desc_value'];
                        $data[$this->pre.'land_time_submit_desc'] = $relation_desc_value;
                        $relation_log_data[]= [
                            'field' => 'land_time',
                            'info' => $relation_desc_value,
                            'label' => '拿地时间',
                            'original_value' =>  $row[$this->pre.'land_time'],
                            'value' => $params['relation_value'],
                            'status' => STATUS_SUBMIT
                        ];

                        $data[$this->pre.'start_construction_time'] = $params['relation_value2'];
                        $data[$this->pre.'start_construction_time_desc'] = $params['relation_value2'];
                        $data[$this->pre.'start_construction_time_status'] = $params['status'];
                        $relation_desc_value2 = (isset($params['relation_desc_value2']) && $params['relation_desc_value2'])?$params['relation_desc_value2']:$params['desc_value'];
                        $data[$this->pre.'start_construction_time_submit_desc'] = $relation_desc_value2;
                        $relation_log_data[]= [
                            'field' => 'start_construction_time',
                            'info' => $relation_desc_value2,
                            'label' => '开工时间',
                            'original_value' =>  $row[$this->pre.'start_construction_time'],
                            'value' => $params['relation_value2'],
                            'status' => STATUS_SUBMIT
                        ];
                    }


                    // if($field == "project_source_ids"  ) {
                    //     $idx = stripos($data[$params_field],"32");
                    //     if($idx !== false)
                    //     {
                    //         $data[$this->pre.'leader_approach_desc'] = $params['relation_value'];
                    //         $data[$this->pre.'leader_approach_desc_desc'] = $params['relation_value'];
                    //         $data[$this->pre.'leader_approach_desc_status'] = $params['status'];
                    //         $relation_desc_value = (isset($params['relation_desc_value']) && $params['relation_desc_value'])?$params['relation_desc_value']:$params['desc_value'];
                    //         $data[$this->pre.'access_time_submit_desc'] = $relation_desc_value;


                    //         $relation_log_data['info'] = $relation_desc_value;  //
                    //         $relation_log_data['label'] = '区领导接洽情况';
                    //         // $relation_log_data[''] = '准入时间';
                    //         $relation_log_data['original_value'] = $row[$this->pre.'leader_approach_desc'];
                    //         $relation_log_data['value'] = $params['relation_value'];
                    //         $relation_log_data['status'] = STATUS_SUBMIT;
                    //     }
                    //     $major_activity = (new \app\admin\model\Activity)->where(['is_important'=>1])->column('id');
                    //     if($data[$params_field])
                    //     {

                    //         $result = array_intersect($major_activity,explode(",",$data[$params_field]));
                    //         if($result)
                    //             $data['is_important'] = 1;
                    //         else if(in_array(22, $data[$params_field]))//区领导见签
                    //             $data['is_important'] = 1;
                    //         else if(in_array(35, $data[$params_field]))//市领导见签
                    //             $data['is_important'] = 1;
                    //         else
                    //             $data['is_important'] = 0;
                    //     }
                    //     else
                    //         $data['is_important'] = 0;

                    // }


                }

                // pr($data);
                // exit();
                // pr($log_data);
                // exit;
                // pr($relation_log_data);

                // 20210125 xiaojia
                // 2020 --->2021 相反同等

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($data);
                    // if(in_array($field,['name','investment_total','framework_agreement_time','invesment_agreement_time','project_source_ids'])){
                    //     $dispatch_row = $this-> dispatchmodel->where(['project_pno'=>$row['pno']])->find();

                    //     if($dispatch_row && $dispatch_row[$field]!=$params['value']) {
                    //         $dispatch_params['tmp_'.$field] = $params['value'] ;
                    //         // $dispatch_params[$field] = $params['value'] ;
                    //         $dispatch_params['tmp_'.$field.'_status'] = 100;
                    //         $dispatch_params['status'] = 1;
                    //         if($field == 'project_source_ids')
                    //             $dispatch_params['tmp_project_source_names'] = $data['tmp_project_source_names'];
                    //         // pr($dispatch_params);
                    //         $dispatch_row->allowField(true)->save($dispatch_params);
                    //     }
                    // }


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if(isset($params['status']) && $params['status'] == STATUS_SUBMIT)
                    {
                        $this->addCheckLog($ids,$field,$log_data);
                        if($field =='is_land'){
                            $this->addCheckLogMulti($ids,$relation_log_data);
                        }else{
                            if(!empty($relation_log_data))
                                $this->addCheckLog($ids,$field,$relation_log_data);
                        }
                    }

                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $list = [];
        foreach ($fields_list as $key => $value) {
            if(!$this->auth->isSuperAdmin() && $value['item_id'] == 'chargedep_ids')
                continue;
            $value['relation_value'] = '';
            $item_required = $value['item_required'] ? json_decode($value['item_required'],true):'';
            $value['item_data_msg'] = '';
            $value['group_style'] = '';
            if($item_required )
            {
                $is_required = $item_required[$library_id]['is_required'];
                $value['item_required'] = $is_required;
                // echo $item_required[$library_id]['is_required'];
                $value['item_data_rule'] = $is_required==1?'data-rule="required"':'';

                $value['item_pending'] = $item_required[$library_id]['is_pending'];

                if($value['item_class'] == 'capital' && $is_required )
                {
                    $value['item_data_rule'] = 'data-rule="required(from, .capital); '.$value['item_id'].'"';
                    $value['item_data_msg'] = 'data-msg-required="内外资至少填一项"';
                }
            }else{
                $value['item_required'] = 0;
                $value['item_data_rule'] = '';
                $value['item_pending'] = 0;
            }
            if($value['item_rule'])
                $value['item_rule'] = json_decode($value['item_rule'],true);
            else
                $value['item_rule'] = [];

            if($value['item_type'] == 'text')
                $value['item_rule'] = empty($value['item_rule']) ? ['row'=>2]:$value['item_rule'];

            $item_rule = $value['item_rule'];

            if($value['item_id'] == 'carrier_id'){
                $row['carrier_id_relation_unit'] = getRelationValue('carrier_id',$row['carrier_id']);
                $row['tmp_carrier_id_relation_unit'] = getRelationValue('carrier_id',$row['tmp_carrier_id']);
            }
            // if(isset($item_rule['is_relation']) && $item_rule['is_relation'] == 1)
            // {
            //     // $realation_id = $item_rule['item_id'];
            //     $value['relation_unit'] = $row[$value['item_id'].'_relation_unit'];
            //     $value['relation_value'] = $row[$this->pre.$value['item_id'].'_relation'];

            // }



            if(($value['item_type'] == 'select' || $value['item_type'] == 'selects') && !empty($value['item_rule']))
            {


                // $item_rule = json_decode($value['item_rule'],true);
                // pr($item_rule);
                if(is_string($item_rule['datasource'])){
                    $tablename = $item_rule['datasource'];
                    $option_where = [];
                    if(isset($item_rule['library']))
                        $option_where['library_id'] = $library_id;
                    if(isset($item_rule['group_id']))
                        $option_where['group_id'] = $item_rule['group_id'];
                    if($value['item_id'] == 'project_source_ids' )
                    {
                        if($library_id == DISCUSS)
                            $option_where['library_id'] = 0;
                        $option_where['year'] = ['in',[0,$this->year]];
                    }
                    // if($value['item_id'] == 'project_source_ids' && $library_id == DISCUSS)
                    //     $option_where['library_id'] = 0;
                    $options = getSelectList($tablename, $option_where);
                }
                else
                    $options = $item_rule['datasource'];

                $first_option = [];
                if($value['item_id']=="planned_street_ids" || $value['item_id']=="settle_street_ids")
                    $first_option = ['-100'=>"待定"];
                $item_rule['datasource'] = $first_option + $options;
                $value['item_rule'] = $item_rule;

            }

            // if($value['item_id'] == 'access_time' )
            // {
            //     if($row['is_access'] == '否' &&  $row['tmp_is_access'] == '否')
            //         $value['group_style'] = 'display:none;';
            // }
            if($value['item_id'] == 'land_time' )
            {
                if($row['is_land'] == '否' &&  $row['tmp_is_land'] == '否')
                    $value['group_style'] = 'display:none;';
            }

            if($value['item_id'] == 'start_construction_time' )
            {
                if($row['is_land'] == '否' &&  $row['tmp_is_land'] == '否')
                    $value['group_style'] = 'display:none;';
            }

            if($value['item_id'] == 'leader_approach_desc') {
                $idx = stripos($row['project_source_ids'],"32");
                $idx2 = stripos($row['tmp_project_source_ids'],"32");
                if($idx === false && $idx2 === false)
                    $value['group_style'] = 'display:none;';
            }
            // if($this->auth->isSuperAdmin()){
            //     $value['after_item_id'] = $value['item_id'];
            //     $value['after_item_value'] = '';
            //     $value['after_item_submit_desc'] = '';
            // }
            // else{
            //     $value['after_item_id'] = 'tmp_'.$value['item_id'];

            //     if($row['tmp_'.$value['item_id']] == PENDING )
            //         $value['after_item_value'] = PENDING_TEXT;
            //     elseif ($row['tmp_'.$value['item_id']] == ZERO ) {
            //         $value['after_item_value'] = '';
            //     }else{



            //         $value['after_item_value'] = $row['tmp_'.$value['item_id']];

            //         if($value['item_type'] == 'date' ) {
            //             $value['after_item_value'] = $row['tmp_'.$value['item_id'].'_desc'];
            //         }
            //         // if($value['item_type'] == 'price' && (int)$row['tmp_'.$value['item_id']] == ZERO) {
            //         //     $value['after_item_value'] = '';
            //         // }
            //     }

            //     // $value['after_item_submit_desc'] = $row['tmp_'.$value['item_id'].'_submit_desc'];

            // }
            // if(!$this->auth->isSuperAdmin())
            //     $value['item_id'] = 'tmp_'.$value['item_id'];
            $list[] = $value;
        }
        $this->assign("row", $row);
        $this -> assign('is_admin',$this -> auth -> isSuperAdmin());
        $this->view->assign("list", $list);
        $this->assignconfig('ids',$ids);
        $this->assignconfig('pno',$row['pno']);
        $this->assign('library_id',$library_id);
        $this->assign('socialized',['name'=>$row['name'],'planned_street_ids'=>$row['planned_street_ids'],'planned_street_names'=>$row['planned_street_names'],'settle_street_ids'=> $row['settle_street_ids'],'settle_street_names'=>$row['settle_street_names'],'investment_name'=>$row['investment_name']]);
        // echo $row->realtion_unit;
        // pr($row->toArray());
        // pr(collection($list)->toArray());

        return $this->view->fetch();
    }
    public function editall($ids = null) {

        if ($this->request->isPost()) {
            $row = $this->model->where('id',$ids)->where($this->whereExtend)->find();
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            // $dispatch_row = $this-> dispatchmodel->where(['project_pno'=>$row['pno']])->find();
            // $dispatch_params = [];
            $fieldData = [];
            $data = [];
            $logalldata = [];
            $library_id = $row['library_id'];
            $field_where = $this->fieldWhere($library_id, ACTION_EDIT);
            $fields_list = Fields::where($field_where)->order('weight','asc')->select();
            foreach ($fields_list as $key => $value) {
                $fieldData[$value['item_id']] = $value;
            }
            $params = $this->request->post("row/a",[]);
            foreach ($params as $field => $value) {
                $log_data = [];

                $field_row = $fieldData[$field];
                if($field_row && $value['value'] )
                {


                    if($value['value'] == PENDING_TEXT)
                        $value['value'] = PENDING;


                    $field_name = str_replace('id','name', $field);

                    $params_field = $this->auth->isSuperAdmin() ? $field :'tmp_'.$field;
                    $params_field_name = str_replace('id','name', $params_field);
                    if($value['value'] == $row[$params_field])
                        continue;
                    $log_data['label'] = $field_row['item_label'];

                    $log_data['original_value'] = $row[$params_field];
                    $log_data['value'] = $value['value'];
                    $log_data['status'] = $value['status'];

                    if(isset($value['desc_value']))
                    {
                        $data[$params_field.'_submit_desc'] = $value['desc_value'];
                        $log_data['info'] = $value['desc_value'];
                    }


                    $data[$params_field] = $value['value'];
                    if($field_row['item_type'] == "select" || $field_row['item_type'] == "selects")
                    {

                        $data[$params_field] = is_array($value['value'])?implode(",",$value['value']):$value['value'];
                        $rule = json_decode($field_row['item_rule'], true);
                        // pr($rule);

                        if(is_string($rule['datasource'])){
                            $tb_name = $rule['datasource'];
                            $data[$params_field_name] =  getSelectText($tb_name,$value['value']);
                        }else
                            $data[$params_field_name] = isset($rule['datasource'][$value['value']])?$rule['datasource'][$value['value']]:'';


                        $log_data['original_value'] = $row[$field_name];
                        $log_data['value'] = $data[$params_field_name];
                    }

                    if($field_row['item_type'] == "datetime" || $field_row['item_type'] == "date")
                    {
                        $log_data['original_value'] = $row[$field.'_desc'];
                        $log_data['value'] = $value['value'];

                        if($value['value'] == PENDING)
                        {
                            $data[$params_field.'_desc'] = PENDING_TEXT;
                        }
                        else
                        {
                            $data[$params_field.'_desc'] = $value['value'];
                            if($row[$params_field] == strtotime($value['value']))
                                continue;
                        }


                    }

                    if($field == "carrier_id")
                    {
                        if($data[$params_field] != '5')
                        {
                            $relaton_log_data = [];
                            $data[$params_field.'_relation'] = $value['relation_value'];

                            if($row[$params_field.'_relation'] == $value['relation_value'])
                                continue;
                            $relation_log_data['original_value'] = $row[$params_field.'_relation'];
                            $relation_log_data['value'] = $value['relation_value'];

                            $relation_log_data['label'] = '载体面积';


                            $relation_log_data['info'] = $value['desc_value'];

                            $relation_log_data['status'] = STATUS_SUBMIT;
                            $logalldata['carrier_id_relation'] = $relation_log_data;
                        }

                    }

                    // if($field_row['item_type'] == "radio"){
                    //     $log_data['original_value'] = $row[$field]? '是':'否';
                    //     $log_data['value'] = $value['value']? '是':'否';
                    // }

                    if(isset($value['status']) && $value['status'] == STATUS_SUBMIT){
                        $data[$params_field.'_status'] = $value['status'];
                        $log_data['status'] = $value['status'];
                        // $log_data['info'] = '修改提交';  //
                    }
                    // if(in_array($field,['name','investment_total','framework_agreement_time','invesment_agreement_time'])){

                    //     if($dispatch_row && $dispatch_row[$field] != $value['value']) {
                    //         $dispatch_params['tmp_'.$field] =  $value['value'] ;
                    //         // $dispatch_params[$field] = $value['value'] ;
                    //         $dispatch_params['tmp_'.$field.'_status'] = 100;
                    //         $dispatch_params['status'] = 1;
                    //     }

                    // }
                    $logalldata[$field] = $log_data;
                }
            }

            // $type = $this->request->post('type',0);
            $result = $row->allowField(true)->save($data);
            if($result )
            {
                foreach ($logalldata as $field => $value) {
                    $this->addCheckLog($ids,$field,$value);
                }
                // pr($dispatch_params);
                // if($dispatch_row)
                //     $dispatch_row->allowField(true)->save($dispatch_params);
            }
            $this->success('提交成功，进入审核状态！');

        }
    }

    public  function initedit($ids) {
        // var_dump($this->model);
        // $row = $this->model->where('id',$ids)->where($this->whereExtend)->find();
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // echo $this->model->getLastSql();
        // $dispatch_row = $this-> dispatchmodel->where(['project_pno'=>$row['pno']])->find();
        // $dispatch_params = [];
        $library_id = $row['library_id'];
        $field_where = $this->fieldWhere($library_id, ACTION_ADD);
        // echo $is_important;
        $fields_list = Fields::where($field_where)->order('weight','asc')->select();
        // echo Fields::getLastSql();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $msg = '提交成功';
            if ($params) {
                $data = [];
                $params = $this->preExcludeFields($params);
                if(isset($params['tmp_name']) && $params['tmp_name'] && $row['name'] != $params['tmp_name'] && !$this->auth->isSuperAdmin())
                {
                    $data['tmp_name'] = $params['tmp_name'];
                    $data['tmp_name_status'] = STATUS_SUBMIT;
                    // $dispatch_params['tmp_name'] = $params['tmp_name'];
                    // $dispatch_params['tmp_name_status'] = STATUS_SUBMIT;
                }
                foreach ($fields_list as $key => $value) {

                    if($this->auth->isSuperAdmin())
                    {
                        $field = $value['item_id'];
                    }
                    else{
                        $field = 'tmp_'.$value['item_id'];
                        $data['status'] = 1;//待审核 这个项目是不是签约库编辑完，更新到旬调度库，然后旬调度库审核了。签约库就会更改成待提交，所以待提交确认后才能使待审核
                        // $data['street_status'] = $staus;
                    }
                    if(!isset($params[$field]))
                        continue;


                    if($params[$field] == '待定'){
                        $params[$field] = PENDING;
                    }

                    if(is_array($params[$field]))
                        $params[$field] = implode(",",$params[$field]);

                    if($row[$value['item_id']] == $params[$field])
                        continue;

                    if($value['item_type'] == "datetime" || $value['item_type'] == "date" ){
                        if($row[$value['item_id'].'_desc'] == $params[$field])
                            continue;
                    }

                    if(isset($params[$field]) && $params[$field])
                    {
                        $data[$field] = $params[$field];
                        if(!$this->auth->isSuperAdmin())
                            $data[$field.'_status'] = STATUS_SUBMIT;

                        if($value['item_type'] == "select" || $value['item_type'] == "selects")
                        {
                            // echo "Aaaa";
                            $rule = json_decode($value['item_rule'], true);
                            $name_field = str_replace('id','name', $field);
                            if(is_string($rule['datasource'])){
                                $tb_name = $rule['datasource'];
                                $data[$name_field] =  getSelectText($tb_name,$params[$field]);
                            }else
                                $data[$name_field] = $rule['datasource'][$params[$field]];


                        }

                        if($value['item_type'] == "datetime" || $value['item_type'] == "date")
                        {
                            if($params[$field] == PENDING)
                                $data[$field.'_desc'] = '待定';
                            else
                                $data[$field.'_desc'] = $params[$field];
                            // $data_params['value'] = $data_params['value'];
                        }

                        if($value['item_id'] == 'carrier_id'){
                            $data[$field.'_relation'] = $params[$field.'_relation'];
                        }


                        // if($value['item_id'] == 'project_source_ids') {
                        //     $major_activity = (new \app\admin\model\Activity)->where(['is_important'=>1])->column('id');
                        //     // $project_source_ids = explode(",",$params[$field]);
                        //     // var_dump($params[$field])
                        //     // exit();
                        //     if(is_array($params[$field]))
                        //     {
                        //         if($params[$field])
                        //         {

                        //             $result = array_intersect($major_activity,explode(",",$params[$field]));
                        //             if($result)
                        //                 $data['is_important'] = 1;
                        //             else
                        //                 $data['is_important'] = 0;
                        //         }
                        //         else
                        //             $data['is_important'] = 0;
                        //     }

                        // }

                        // if(in_array($value['item_id'],['name','investment_total','framework_agreement_time','invesment_agreement_time','project_source_ids']) && $dispatch_row && $dispatch_row[$value['item_id']] != $params[$field]){

                        //     $dispatch_params['tmp_'.$value['item_id']] =  $params[$field] ;
                        //     // $dispatch_params[$field] = $value['value'] ;
                        //     $dispatch_params['tmp_'.$field.'_status'] = 100;
                        //     if($field == 'project_source_ids')
                        //         $dispatch_params['tmp_project_source_names'] = $data['tmp_project_source_names'];
                        //     $dispatch_params['status'] = 1;


                        // }
                    }
                }

                // echo $params["{$this->pre}project_socialized"];
                // if(isset($params["{$this->pre}project_socialized"]) ) {
                //     $data["{$this->pre}project_socialized"] = $params["{$this->pre}project_socialized"];
                //     if(!$this->auth->isSuperAdmin())
                //         $data["{$this->pre}project_socialized_status"] = STATUS_SUBMIT;
                //     if($params["{$this->pre}project_socialized"] == '是'){
                //         foreach($this->project_socialized as $key => $value) {
                //             if($this->auth->isSuperAdmin())
                //             {
                //                 $field = $value['item_id'];
                //             }
                //             else{
                //                 $field = 'tmp_'.$value['item_id'];
                //                 // $data['street_status'] = $staus;
                //             }

                //             if(isset($params[$field]) && $params[$field])
                //             {
                //                 $data[$field] = $params[$field];
                //                 if(!$this->auth->isSuperAdmin())
                //                     $data[$field.'_status'] = STATUS_SUBMIT;

                //                 if($value['item_type'] == "datetime" || $value['item_type'] == "date")
                //                 {
                //                     $data[$field.'_desc'] = $params[$field];
                //                 }
                //             }
                //         }
                //     }

                // }
                // var_dump($data);
                // exit('11111111111');
                // var_dump($msg);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($data);
                    // if($dispatch_row && $dispatch_params)
                    //     $dispatch_row->allowField(true)->save($dispatch_params);

                    // // 超级管理员提交
                    // if($this->auth->isSuperAdmin())
                    // {
                    //     if($data['is_command']=='是'||$row['is_command']=='是')
                    //     {
                    //         $command_data = [];
                    //         $command_data= [
                    //             'project_pno'=>$row['pno'],
                    //             'name'=>$row['name'],
                    //             'access_time'=>$data['tmp_access_time']?$data['tmp_access_time']:$row['access_time'],
                    //             'access_time_desc'=>$data['tmp_access_time_desc']?$data['tmp_access_time_desc']:$row['access_time_desc'],

                    //             'sign_time'=>$data['tmp_sign_time']?$data['tmp_sign_time']:$row['sign_time'],
                    //             'sign_time_desc'=>$data['tmp_sign_time_desc']?$data['tmp_sign_time_desc']:$row['sign_time_desc'],

                    //             'framework_agreement_time'=>$data['tmp_framework_agreement_time']?$data['tmp_framework_agreement_time']:$row['framework_agreement_time'],
                    //             'framework_agreement_time_desc'=>$data['tmp_framework_agreement_time_desc']?$data['tmp_framework_agreement_time_desc']:$row['framework_agreement_time_desc'],

                    //             'invesment_agreement_time'=>$data['tmp_invesment_agreement_time']?$data['tmp_invesment_agreement_time']:$row['invesment_agreement_time'],
                    //             'invesment_agreement_time_desc'=>$data['tmp_invesment_agreement_time_desc']?$data['tmp_invesment_agreement_time_desc']:$row['invesment_agreement_time_desc'],

                    //             'register_time'=>$data['tmp_register_time']?$data['tmp_register_time']:$row['register_time'],
                    //             'register_time_desc'=>$data['tmp_register_time_desc']?$data['tmp_register_time_desc']:$row['register_time_desc'],

                    //             'land_time'=>$data['tmp_land_time']?$data['tmp_land_time']:$row['land_time'],
                    //             'land_time_desc'=>$data['tmp_land_time_desc']?$data['tmp_land_time_desc']:$row['land_time_desc'],

                    //             'start_construction_time'=>$data['tmp_start_construction_time']?$data['tmp_start_construction_time']:$row['start_construction_time'],
                    //             'start_construction_time_desc'=>$data['tmp_start_construction_time_desc']?$data['tmp_start_construction_time_desc']:$row['start_construction_time_desc'],
                    //             'command_type'=>$data['command_type']?$data['command_type']:$row['command_type'],
                    //         ];

                    //         // 更新command 表
                    //         if (!empty($command_data)){
                    //             $row_command = \app\admin\model\Command::where(['project_pno'=>$row['pno']])->find();
                    //             if(!isset($row_command))
                    //                 \app\admin\model\Command::create($command_data);
                    //             else
                    //                 \app\admin\model\Command::where(['project_pno'=>$row['pno']])->update($command_data);
                    //         }
                    //     }
                    // }

                    // $result = $this->model->allowField(true)->save($data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    // $row = $this->model->get($this->model->id);
                    // $this->addCheckLog($row, '', ['status'=>STATUS_CREATE]);


                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $list = [];

        foreach ($fields_list as $key => $value) {
            if(!$this->auth->isSuperAdmin() && $value['item_id'] == 'chargedep_ids')
                continue;

            $item_required = $value['item_required'] ? json_decode($value['item_required'],true):'';
            // pr($item_required );
            // echo $value['item_label'];
            // echo $value['item_class'];
            $value['item_data_msg'] = '';
            $value['item_required'] = 0;
            $value['item_data_rule'] = '';
            $value['item_pending'] = 0;

            if($item_required && !$this->auth->isSuperAdmin())
            {
                $value['item_pending'] = $item_required[$library_id]['is_pending'];
                if($this->auth->isSuperAdmin()){
                    if($value['item_id'] == 'chargedep_ids')
                    {
                        $value['item_required'] = 1;
                        $value['item_data_rule'] = 'data-rule="required"';
                    }
                }
                else{

                    $is_required = $item_required[$library_id]['is_required'];
                    $value['item_required'] = $is_required;
                    $value['item_data_rule'] = $is_required==1?'data-rule="required"':'';

                    if($value['item_class'] == 'capital' && $is_required )
                    {
                        $value['item_data_rule'] = 'data-rule="required(from, .capital);"';
                        $value['item_data_msg'] = 'data-msg-required="内外资至少填一项"';
                    }

                    if($value['item_class'] == 'agreement' && $is_required )
                    {
                        $value['item_data_rule'] = 'data-rule="required(from, .agreement);"';
                        $value['item_data_msg'] = 'data-msg-required="框架与正式协议至少填一项"';
                    }
                }

            }


            if($value['item_rule'])
                $value['item_rule'] = json_decode($value['item_rule'],true);
            else
                $value['item_rule'] = [];

            $item_rule = $value['item_rule'];

            if($value['item_type'] == 'text')
                $value['item_rule'] = empty($value['item_rule']) ? ['row'=>2]:$value['item_rule'];



            if($value['item_type'] == 'select' || $value['item_type'] == 'selects')
            {
                $options = [];
                if($item_rule)
                {
                    // $item_rule = json_decode($value['item_rule'],true);
                    // pr($item_rule);
                    if(is_string($item_rule['datasource'])){
                        $tablename = $item_rule['datasource'];
                        $option_where = [];
                        if(isset($item_rule['library']))
                            $option_where['library_id'] = $library_id;
                        if(isset($item_rule['group_id']))
                            $option_where['group_id'] = $item_rule['group_id'];
                        if($value['item_id'] == 'project_source_ids' && $library_id == DISCUSS)
                            $option_where['library_id'] = 0;
                        $options = getSelectList($tablename, $option_where);
                        // $options = getSelectList($tablename);
                    }
                    else
                        $options = $item_rule['datasource'];
                    $item_rule['datasource'] = $options;
                    $value['item_rule'] = $item_rule;
                }
            }
            $value['div_class'] = 'div-'.$value['item_id'];
            $value['original_item_id'] = $value['item_id'];

            if(!$this->auth->isSuperAdmin())
            {
                $value['item_id'] = 'tmp_'.$value['item_id'];

            }
            // pr($value->toArray());
            $list[] = $value;
        }
        $this->view->assign("list", $list);
        $this->view->assign("pre", $this->auth->isSuperAdmin()?"":"tmp_");
        $this->assign("libary_id",$library_id);
        $this->assign("row",$row);
        return $this->view->fetch();
    }
    public function checkedit($ids = null) {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $library_id = $row['library_id'];
        $field_where = $this->fieldWhere($library_id, ACTION_EDIT);
        $fields_list = Fields::where($field_where)->order('weight','asc')->select();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }


        $list = [];
        foreach ($fields_list as $key => $value) {
            // if(isset($row["tmp_{$value['item_id']}_status"]) && $row["tmp_{$value['item_id']}_status"] == STATUS_SUBMIT)
            // {
            $value['relation_value'] = '';
            $item_required = $value['item_required'] ? json_decode($value['item_required'],true):'';
            $value['item_data_msg'] = '';
            if($item_required)
            {
                $is_required = $item_required[$library_id]['is_required'];
                $value['item_required'] = $is_required;
                // echo $item_required[$library_id]['is_required'];
                $value['item_data_rule'] = $is_required==1?'data-rule="required"':'';

                $value['item_pending'] = $item_required[$library_id]['is_pending'];

                if($value['item_class'] == 'capital' && $is_required )
                {
                    $value['item_data_rule'] = 'data-rule="required(from, .capital); '.$value['item_id'].'"';
                    $value['item_data_msg'] = 'data-msg-required="内外资至少填一项"';
                }
            }else{
                $value['item_required'] = 0;
                $value['item_data_rule'] = '';
                $value['item_pending'] = 0;
            }
            if($value['item_rule'])
                $value['item_rule'] = json_decode($value['item_rule'],true);
            else
                $value['item_rule'] = [];
            $item_rule = $value['item_rule'];
            if($value['item_type'] == 'text')
                $value['item_rule'] = empty($value['item_rule']) ? ['row'=>2]:$value['item_rule'];

            // if(isset($item_rule['is_relation']) && $item_rule['is_relation'] == 1)
            // {
            //     // $realation_id = $item_rule['item_id'];
            //     $value['relation_unit'] = $row[$this->pre.$value['item_id'].'_relation_unit'];
            //     $value['relation_value'] = $row[$this->pre.$value['item_id'].'_relation'];

            // }
            $list[] = $value;
        }
        // }
        // if($row['tmp_project_socialized'] == '1' && $row['tmp_project_socialized_status'] == STATUS_SUBMIT)
        // {
        //     $list[] = [
        //         'item_id' => 'project_socialized',
        //         'item_type' => 'radio',
        //         'item_label' => '社会化招商'
        //     ];
        //     foreach ($this->project_socialized as $key => $value) {
        //         if(isset($row["tmp_{$value['item_id']}_status"]) && $row["tmp_{$value['item_id']}_status"] == STATUS_SUBMIT)
        //         {
        //             $list[] = $value;
        //         }
        //     }
        // }
        // $this->assign('empty','<span class="empty">暂无审核项</span>');
        $this->view->assign("row", $row);
        $this->view->assign("list", $list);
        // $this->view->assign("project_socialized", $this->project_socialized);
        $this->assignconfig('ids',$ids);
        $this->assignconfig('pno',$row['pno']);
        // pr(collection($list)->toArray());
        return $this->view->fetch();
    }


    public function detail($ids = null) {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // echo $this->model->getLastSql();
        $library_id = $row['library_id'];
        $field_where = $this->fieldWhere($library_id);
        $list = Fields::where($field_where)->order('weight','asc')->select();

        $data = [];
        foreach ($list as $key => $value) {
            $data[$key]['item_label'] = $value['item_label'];
            switch ($value['item_type']) {
                case 'text':
                case 'textarea':
                case 'price':
                    $data[$key]['item_value'] = $row[$value['item_id']] == -100?'待定':$row[$value['item_id']];

                    break;
                case 'date':
                case 'datatime':
                    $data[$key]['item_value'] = $row[$value['item_id'].'_desc'];
                    break;
                case 'select':
                case 'selects':
                    $data[$key]['item_value'] = $row[str_replace('id','name',$value['item_id'])];
                    break;
                // case 'radio':
                //     $data[$key]['item_value'] = $row[$value['item_id']]==1?'是':'否';
                //     break;
                default:
                    $data[$key]['item_value'] = '-';
                    break;
            }
        }
        // $this->view->assign("list", $list);
        $this->view->assign("name", $row->name);
        $this->view->assign("row", $row);

        // $this->assign('data',$data);
        $this->assign('count',count($data));
        $this->assignconfig('ids',$ids);
        // pr(collection($list)->toArray());
        if($library_id == 1)
            return $this->view->fetch('detail_discuss');
        if($library_id == 2)
            return $this->view->fetch('detail_signed');
    }

    public function checkpass($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $field = $this->request->post("item_id");
        // echo  $row['tmp_'.$field];exit();
        if(!$field)
            $this->error(__('字段名不存在'));
        $data = [];
        $log_data = [];
        $relation_log_data = [];
        $field_row = Fields::where(['table_name'=>$this->fields_tablename, 'item_id'=>$field])->find();
        $data[$field] = $row['tmp_'.$field];
        $data['tmp_'.$field] = null;
        $data['tmp_'.$field.'_submit_desc'] = null;
        $data['tmp_'.$field.'_status'] = STATUS_PASS;
        // $data['is_add'] = 0;



        $log_data['original_value'] = $row[$field];
        $log_data['value'] = $row['tmp_'.$field];
        $log_data['status'] = STATUS_PASS;
        $log_data['label'] = $field_row['item_label'];
        $log_data['info'] = $row['tmp_'.$field.'_submit_desc'];  //

        if($field_row['item_type'] == 'select' || $field_row['item_type'] == 'selects')
        {
            $name_field = str_replace('id','name',$field);
            $data[$name_field] = $row['tmp_'.$name_field];
            $data['tmp_'.$name_field] = '';

            $log_data['original_value'] = $row[$name_field];
            $log_data['value'] = $row['tmp_'.$name_field];
        }
        if($field_row['item_type'] == "datetime" ||$field_row['item_type'] == "date")
        {
            $data[$field.'_desc'] = $row['tmp_'.$field.'_desc'];
            $data['tmp_'.$field.'_desc'] = null;

            $log_data['original_value'] = $row[$field.'_desc'];
            $log_data['value'] = $row['tmp_'.$field.'_desc'];

        }

        if($field == 'framework_agreement_time' || $field == 'invesment_agreement_time') {
            $data['library_id'] = 2;
            $data['library_name'] = '签约库';
        }

        if($field == "carrier_id" && $row['tmp_'.$field] != '5')
        {

            $data[$field.'_relation'] = $row['tmp_'.$field.'_relation'];
            $data['tmp_'.$field.'_relation'] = null;
            $relation_log_data = $log_data;
            $relation_log_data['label'] = '载体面积';
            $relation_log_data['original_value'] = $row[$field."_relation"];
            $relation_log_data['value'] = $row['tmp_'.$field."_relation"];

        }
        $data['is_visible'] =1;

        // 准入例会上会
        // $access_data = [];
        // if($field=='is_access'&& $row['tmp_'.$field] == '是') {
        //     // $progress_info = \app\admin\model\Progress::where(['id'=>$row['progress_status_id']])->find();
        //     $access_data= [
        //         'pno'=>$row['pno'],
        //         'name'=>$row['name'],
        //         'investment_name'=>$row['investment_name'],
        //         'investment_total'=>$row['investment_total'],
        //         'summary'=>$row['summary'],
        //         'exist_question'=>$row['problem'],
        //         'status'=>$row['progress_status_id'],
        //         'status_name'=>$row['progress_status_name'],
        //         'chargedep_ids'=>$row['chargedep_ids'],
        //         'chargedep_names'=>$row['chargedep_names'],
        //         'settle_street_ids'=>$row['chargedep_ids'],
        //         'settle_street_names'=>$row['chargedep_names'],
        //         'land_time'=>$row['land_time'],
        //         'create_time'=>time(),
        //         'update_time'=>time(),
        //     ];
        // }
        // pr($access_data);exit();

        // 20210125 xiaojia
        // 单个审核，2020 --->2021 相反同等
        // if($this->project_tablename == 'nsig_project_2020')
        // {
        //     $this->update_model = new \app\admin\model\Project_2021();
        //     $row_update = $this->update_model->where(['name'=>$row->name])->find();
        // }else if($this->project_tablename == 'nsig_project_2021'){
        //     $this->update_model = new \app\admin\model\Project();
        //     $row_update = $this->update_model->where(['name'=>$row->name])->find();
        // }

        $result = $row->allowField(true)->save($data);
        if ($result !== false) {
            $this->addCheckLog($ids,$field,$log_data);
            if(!empty($relation_log_data)){
                $this->addCheckLog($ids,$field,$relation_log_data);
            }
            // if(!empty($access_data))
            // {
            //     $row_access = \app\admin\model\Access::where(['pno'=>$row['pno']])->find();
            //     if(!isset($row_access))
            //         \app\admin\model\Access::create($access_data);
            //     else
            //         \app\admin\model\Access::where(['pno'=>$row['pno']])->update($access_data);
            // }

            // 更新command 表
            // if (!empty($command_data)){
            //     $row_command = \app\admin\model\Command::where(['project_pno'=>$row['pno']])->find();
            //     if(!isset($row_command))
            //         \app\admin\model\Command::create($command_data);
            //     else
            //         \app\admin\model\Command::where(['project_pno'=>$row['pno']])->update($command_data);
            // }

            // 更新
            // if(isset($row_update))
            //     $row_update->allowField(true)->save($data);

            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }

    public function checkpass_all($ids = null){
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $data = [];
            $logdataAll = [];
            $library_id = $row['library_id'];
            $field_where = $this->fieldWhere($library_id);
            $field_list = [];
            $field_res = Fields::where($field_where)->order('weight','asc')->select();
            foreach ($field_res as $key => $value) {
                $field = $value['item_id'];
                // if($field == "chargedep_ids")
                //     continue;
                $tmp_field = 'tmp_'.$field;
                $tmp_field_status = 'tmp_'.$field.'_status';
                // $data= [];
                $log_data = [];
                $relation_log_data = [];
                if(isset($row[$tmp_field]) && $row[$tmp_field_status] == STATUS_SUBMIT)
                {
                    $original_value = $row[$field];
                    $temp_value = $row['tmp_'.$field];
                    $submit_desc = $row['tmp_'.$field.'_submit_desc'];

                    $data[$field] = $row['tmp_'.$field];
                    $data['tmp_'.$field] = null;
                    $data['tmp_'.$field.'_submit_desc'] = null;
                    $data['tmp_'.$field.'_status'] = STATUS_PASS;
                    // $data['is_add'] = 0;

                    $log_data['project_pno'] = $row->pno;
                    $log_data['project_name'] = $row->name;
                    $log_data['operator_id'] = $this -> auth -> id;
                    $log_data['operator_nickname'] = $this -> auth -> nickname;
                    $log_data['operate_desc'] = '审核通过';
                    $log_data['operate_field'] = $value['item_id'];
                    $log_data['operate_field_label'] = $value['item_label'];
                    $log_data['operate_original_value'] = $row[$field];
                    $log_data['operate_value'] = $row['tmp_'.$field];
                    $log_data['operate_status'] = STATUS_PASS;
                    $log_data['operate_info'] = $submit_desc;
                    $log_data['table_name'] = $this->tablename;


                    if($value['item_type'] == 'select' || $value['item_type'] == 'selects')
                    {
                        $name_field = str_replace('id','name',$field);
                        $data[$name_field] = $row['tmp_'.$name_field];
                        $data['tmp_'.$name_field] = null;

                        $log_data['operate_field_label'] = $row[$name_field];
                        $log_data['operate_value'] = $row['tmp_'.$name_field];
                    }
                    if($value['item_type'] == "datetime" ||$value['item_type'] == "date")
                    {
                        $data[$field.'_desc'] = $row['tmp_'.$field.'_desc'];
                        $data['tmp_'.$field.'_desc'] = null;

                        $log_data['operate_field_label'] = $row[$field.'_desc'];
                        $log_data['operate_value'] = $row['tmp_'.$field.'_desc'];

                    }
                    // if($value['item_type'] == 'radio')
                    // {

                    //     $log_data['operate_field_label'] = $row[$field]? '是':'否';
                    //     $log_data['operate_value'] = $row['tmp_'.$field]? '是':'否';
                    // }



                    if($field == "carrier_id" && $row['tmp_'.$field] != '5')
                    {
                        $data[$field.'_relation'] = $row['tmp_'.$field.'_relation'];
                        $data['tmp_'.$field.'_relation'] = null;

                        $relation_log_data['project_pno'] = $row->pno;
                        $relation_log_data['project_name'] = $row->name;
                        $relation_log_data['operator_id'] = $this -> auth -> id;
                        $relation_log_data['operator_nickname'] = $this -> auth -> nickname;
                        $relation_log_data['operate_desc'] = '审核通过';
                        $relation_log_data['operate_field'] = 'carrier_id_relation';
                        $relation_log_data['operate_field_label'] = '载体面积';
                        $relation_log_data['operate_original_value'] = $row[$field."_relation"];
                        $relation_log_data['operate_value'] = $row['tmp_'.$field."_relation"];
                        $relation_log_data['operate_status'] = STATUS_PASS;
                        $relation_log_data['operate_info'] = $submit_desc;
                        $relation_log_data['table_name'] = $this->tablename;


                    }
                    $logdataAll[] = $log_data;
                    if(!empty($relation_log_data))
                        $logdataAll[] = $relation_log_data;
                }

            }
            // if($row['tmp_project_socialized']== '是'  && $row['tmp_project_socialized'] == STATUS_SUBMIT)
            // {
            //     $data['project_socialized'] = $row['tmp_project_socialized'];
            //     $data['tmp_project_socialized'] = null;
            //     $data['tmp_project_socialized_submit_desc'] = null;
            //     $data['tmp_project_socialized_status'] = STATUS_PASS;
            //     $logdataAll[] = [
            //         'project_pno'=>$row->pno,
            //         'project_name'=>$row->name,
            //         'operator_id' => $this -> auth -> id,
            //         'operator_nickname' => $this -> auth -> nickname,
            //         'operate_desc' => '审核通过',
            //         'operate_field'=> 'project_socialized',
            //         'operate_field_label' => '社会化招商',
            //         'operate_original_value' => $row['project_socialized'],
            //         'operate_value' =>$row['tmp_project_socialized'],
            //         'operate_status' => STATUS_PASS,
            //         'table_name' => $this->tablename
            //     ];
            //     foreach ($this->project_socialized as $key => $value) {
            //         $field = $value['item_id'];
            //         $tmp_field = 'tmp_'.$field;
            //         $tmp_field_status = 'tmp_'.$field.'_status';
            //         // $data= [];
            //         $log_data = [];
            //         if(isset($row[$tmp_field]) && $row[$tmp_field_status] == STATUS_SUBMIT)
            //         {
            //             $data[$field] = $row['tmp_'.$field];
            //             $data['tmp_'.$field] = null;
            //             $data['tmp_'.$field.'_submit_desc'] = null;
            //             $data['tmp_'.$field.'_status'] = STATUS_PASS;
            //             $log_data['project_pno'] = $row->pno;
            //             $log_data['project_name'] = $row->name;
            //             $log_data['operator_nickname'] = $this -> auth -> nickname;
            //             $log_data['operate_desc'] = '审核通过';
            //             $log_data['operate_field'] = $value['item_id'];
            //             $log_data['operate_field_label'] = $value['item_label'];
            //             $log_data['operate_original_value'] = $row[$field];
            //             $log_data['operate_value'] = $row['tmp_'.$field];
            //             $log_data['operate_status'] = STATUS_PASS;
            //             $log_data['operate_field_label'] = $value['item_label'];
            //             $log_data['operate_info'] = $row['tmp_'.$field.'_submit_desc'];  //
            //             $log_data['table_name'] = $this->tablename;


            //             if($value['item_type'] == "datetime" ||$value['item_type'] == "date")
            //             {
            //                 $data[$field.'_desc'] = $row['tmp_'.$field.'_desc'];
            //                 $data['tmp_'.$field.'_desc'] = null;

            //                 $log_data['operate_original_value'] = $row[$field.'_desc'];
            //                 $log_data['operate_value'] = $row['tmp_'.$field.'_desc'];

            //             }


            //             // if($field == 'framework_agreement_time' || $field == 'invesment_agreement_time') {
            //             //     $data['library_id'] = 2;
            //             //     $data['library_name'] = '签约库';
            //             //     // $data['settle_street_id'] = $row['planned_street_id'];
            //             //     // $data['settle_street_name'] = $row['planned_street_name'];
            //             // }

            //             $logdataAll[] = $log_data;
            //         }
            //     }
            // }

            $data['is_visible'] = 1;
            $data['status'] = 0;
            // pr($logdataAll);
            // $access_data = [];
            // if(isset($data['is_access']) && $data['is_access']=='是') {
            //     $access_data= [
            //         'pno'=>$row['pno'],
            //         'name'=>$row['name'],
            //         'investment_name'=>$row['investment_name'],
            //         'investment_total'=>$row['investment_total'],
            //         'summary'=>$row['summary'],
            //         'exist_question'=>$row['problem'],
            //         'status'=>$row['progress_status_id'],
            //         'status_name'=>$row['progress_status_name'],
            //         'chargedep_ids'=>$row['chargedep_ids'],
            //         'chargedep_names'=>$row['chargedep_names'],
            //         'settle_street_ids'=>$row['chargedep_ids'],
            //         'settle_street_names'=>$row['chargedep_names'],
            //         'land_time'=>$row['land_time'],
            //         'create_time'=>time(),
            //         'update_time'=>time(),
            //     ];
            // }

            // // 全部审核的同时
            // $command_data = [];
            // if($row['is_command']=='是' || $data['is_command']=='是') {
            //     $command_data= [
            //         'project_pno'=>$row['pno'],
            //         'name'=>$row['name'],
            //         'access_time'=>$row['tmp_access_time']?$row['tmp_access_time']:$row['access_time'],
            //         'access_time_desc'=>$row['tmp_access_time_desc']?$row['tmp_access_time_desc']:$row['access_time_desc'],

            //         'sign_time'=>$row['tmp_sign_time']?$row['tmp_sign_time']:$row['sign_time'],
            //         'sign_time_desc'=>$row['tmp_sign_time_desc']?$row['tmp_sign_time_desc']:$row['sign_time_desc'],

            //         'framework_agreement_time'=>$row['tmp_framework_agreement_time']?$row['tmp_framework_agreement_time']:$row['framework_agreement_time'],
            //         'framework_agreement_time_desc'=>$row['tmp_framework_agreement_time_desc']?$row['tmp_framework_agreement_time_desc']:$row['framework_agreement_time_desc'],

            //         'invesment_agreement_time'=>$row['tmp_invesment_agreement_time']?$row['tmp_invesment_agreement_time']:$row['invesment_agreement_time'],
            //         'invesment_agreement_time_desc'=>$row['tmp_invesment_agreement_time_desc']?$row['tmp_invesment_agreement_time_desc']:$row['invesment_agreement_time_desc'],

            //         'register_time'=>$row['tmp_register_time']?$row['tmp_register_time']:$row['register_time'],
            //         'register_time_desc'=>$row['tmp_register_time_desc']?$row['tmp_register_time_desc']:$row['register_time_desc'],

            //         'land_time'=>$row['tmp_land_time']?$row['tmp_land_time']:$row['land_time'],
            //         'land_time_desc'=>$row['tmp_land_time_desc']?$row['tmp_land_time_desc']:$row['land_time_desc'],

            //         'start_construction_time'=>$row['tmp_start_construction_time']?$row['tmp_start_construction_time']:$row['start_construction_time'],
            //         'start_construction_time_desc'=>$row['tmp_start_construction_time_desc']?$row['tmp_start_construction_time_desc']:$row['start_construction_time_desc'],

            //         'command_type'=>$row['tmp_command_type']?$row['tmp_command_type']:$row['command_type'],
            //     ];
            // }

            // 20210125 xiaojia
            // 单个审核，2020 --->2021 相反同等
            // if($this->project_tablename == 'nsig_project_2020')
            // {
            //     $this->update_model = new \app\admin\model\Project_2021();
            //     $row_update = $this->update_model->where(['name'=>$row->name])->find();
            // }else if($this->project_tablename == 'nsig_project_2021'){
            //     $this->update_model = new \app\admin\model\Project();
            //     $row_update = $this->update_model->where(['name'=>$row->name])->find();
            // }
            //


            $result = $row->allowField(true)->save($data);
            if ($result !== false) {
                (new \app\admin\model\ProjectChecklog)->allowField(true)->saveAll($logdataAll);
                // $this->addCheckLog($row,$field,$log_data);

                // if (!empty($access_data)){
                //     $row_access = \app\admin\model\Access::where(['pno'=>$row['pno']])->find();
                //     if(!isset($row_access))
                //         \app\admin\model\Access::create($access_data);
                //     else
                //         \app\admin\model\Access::where(['pno'=>$row['pno']])->update($access_data);
                // }

                // // 更新command 表
                // if (!empty($command_data)){
                //     $row_command = \app\admin\model\Command::where(['project_pno'=>$row['pno']])->find();
                //     if(!isset($row_command))
                //         \app\admin\model\Command::create($command_data);
                //     else
                //         \app\admin\model\Command::where(['project_pno'=>$row['pno']])->update($command_data);
                // }
                // // 更新
                // if(isset($row_update))
                //     $row_update->allowField(true)->save($data);

                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }

    }
    public function checkreject($ids=null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $field = $this->request->post("item_id");
        if(!$field)
            $this->error(__('字段名不存在'));

        $field_row = Fields::where(['table_name'=>$this->fields_tablename, 'item_id'=>$field])->find();
        $reject_desc = $this->request->post("reject_desc");
        $data['tmp_'.$field.'_reject_desc'] = $reject_desc;
        $data['tmp_'.$field.'_status'] = STATUS_REJECT;

        $log_data = $this->getRowValue($row, $field_row, $field);
        $log_data['status'] = STATUS_REJECT;
        $log_data['info'] = $reject_desc;

        // pr($data);
        // pr($log_data);

        $result = $row->allowField(true)->save($data);
        if ($result !== false) {
            $this->addCheckLog($ids,$field,$log_data);
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }

    }

    public function checkrevokereject($ids=null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $field = $this->request->post("item_id");
        if(!$field)
            $this->error(__('字段名不存在'));

        $field_row = Fields::where(['table_name'=>$this->fields_tablename, 'item_id'=>$field])->find();

        $data['tmp_'.$field.'_status'] = STATUS_SUBMIT;
        $data['tmp_'.$field.'_reject_desc'] = null;

        // pr($data);
        // pr($log_data);

        $result = $row->allowField(true)->save($data);
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }

    }

    public function clearvalue($ids=null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $field = $this->request->post("item_id");
        if(!$field)
            $this->error(__('字段名不存在'));

        $field_row = Fields::where(['table_name'=>$this->fields_tablename, 'item_id'=>$field])->find();
        $data = [];
        $data[$field] = null;
        $data['tmp_'.$field] = null;
        $data['tmp_'.$field.'_status'] = STATUS_PASS;
        $data['tmp_'.$field.'_submit_desc'] = null;
        $data['tmp_'.$field.'_reject_desc'] = null;
        if($field_row['item_type'] == 'date'){
            $data[$field.'_desc'] = null;
            $data['tmp_'.$field.'_desc'] = null;
        }

        if($field_row['item_rule'])
        {
            $item_rule = json_decode($field_row['item_rule'],true);
            if(isset($item_rule['is_relation']))
            {
                $data[$field.'_relation'] = null;
                $data['tmp_'.$field.'_relation'] = null;
            }
        }
        // pr($data);
        // pr($log_data);

        $logdata['desc'] = '清空内容';
        $logdata['label'] = $field_row['item_label'];
        $logdata['original_value'] = $row[$field];
        $logdata['value'] = '';
        $logdata['info'] = '';
        $logdata['status'] = STATUS_PASS;

        $result = $row->allowField(true)->save($data);
        if ($result !== false) {
            $this->addCheckLog($ids,$field,$logdata);
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }
    public function nomodify($ids)
    {
        if(!$this->auth->isSuperAdmin())
        {
            $chargedep_data = $this->auth->getChargedep();

            if(!$chargedep_data)
                $this->error('您还未绑定部门或街道');

            $chargedep_id = $chargedep_data->chargedep_id;
            $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
        }


        $row = $this->model->where('id',$ids)->where($this->whereExtend)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if($row['required_text'])
            $this->error('请填写以下：<br>'.$row['required_text'].'信息');
        if($row->status == -1)
        {
            $row->status = 0;
            $row->save();
            $this->success();
        }else{
            $this->error(__('项目已在待审核或已审核状态，无需操作！'));
        }
    }

    public function mark($ids=null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($this->request->isAjax()){
            $type = $this->request->param('type',0);
            $row->is_add = $type;
            $row->save();
            $this->success();
        }

    }

    public function convertcheck() {

    }
    public function convert($ids=null){
        // var_dump("aaaa");
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // if($row->status == 1)
        //     $this->error(__('项目中还有待审核项，需管理员审核后才可转入'));
        if($this->request->isAjax()){
            $data= [
                'library_id'=>2,
                'library_name' => '签约库',
                'is_add' =>1,
                'is_visible' => 0,
                'status' => -1,
                'convert_memo' => '在谈转签约',
                'tmp_progress_status_id' => null,
                'tmp_progress_status_name' => null,
                'tmp_progress_status_status' => null
            ];

            $row->allowField(true)->save($data);
            $this->success();
        }
    }

    public function convert_major($ids=null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($this->request->isAjax()){
            $row->is_access = 1;
            $row->save();
            $this->success();
        }
    }
    public function rejectmemo($ids = null){
        if(!$this->auth->isSuperAdmin())
        {
            $chargedep_data = $this->auth->getChargedep();

            if(!$chargedep_data)
                $this->error('您还未绑定部门或街道');

            $chargedep_id = $chargedep_data->chargedep_id;
            $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
        }


        $row = $this->model->where('id',$ids)->where($this->whereExtend)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }


        // 设置项目状态的同时，2020 --->2021 相反同等
        if($this->project_tablename == 'nsig_project_2020')
        {
            $this->update_model = new \app\admin\model\Project_2021();
            $row_update = $this->update_model->where(['name'=>$row->name])->find();
        }else if($this->project_tablename == 'nsig_project_2021'){
            $this->update_model = new \app\admin\model\Project();
            $row_update = $this->update_model->where(['name'=>$row->name])->find();
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['reject_memo_status'] = 1;
            $result = false;
            $result = $row->allowField(true)->save($params);
            if ($result !== false) {

                // 更新
                if(isset($row_update))
                    $row_update->allowField(true)->save($params);

                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->assign('row',$row);
        return $this->view->fetch();
    }

    public function addsuspend($ids = null){
        if(!$this->auth->isSuperAdmin())
        {
            $chargedep_data = $this->auth->getChargedep();

            if(!$chargedep_data)
                $this->error('您还未绑定部门或街道');

            $chargedep_id = $chargedep_data->chargedep_id;
            $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
        }


        $row = $this->model->where('id',$ids)->where($this->whereExtend)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // 设置项目状态的同时，2020 --->2021 相反同等
            if($this->project_tablename == 'nsig_project_2020')
            {
                $this->update_model = new \app\admin\model\Project_2021();
                $row_update = $this->update_model->where(['name'=>$row->name])->find();
            }else if($this->project_tablename == 'nsig_project_2021'){
                $this->update_model = new \app\admin\model\Project();
                $row_update = $this->update_model->where(['name'=>$row->name])->find();
            }
            // else if($this->project_tablename == 'nsig_project_2020_real'){
            // }
            // var_dump($row->name);exit();
            //
            // $params['reject_memo_status'] = 1;
            $result = false;
            $result = $row->allowField(true)->save($params);
            if ($result !== false) {
                // 更新
                if(isset($row_update))
                    $row_update->allowField(true)->save($params);

                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $suspendselect =  [1=>__('终止'), 2=>__('暂停（不妥实）'),3=>'重复包装'];
        if($this->auth->isSuperAdmin())
            $suspendselect['0'] = '取消/未设置';
        // pr($suspendselect);
        $this->assign('suspendselect',$suspendselect);
        $this->assign('row',$row);
        return $this->view->fetch();
    }

    public function importdiscuss() {
        // $fields = ['sort','street_name','name','investment_total','desc','progression','problem','next_measure','access_time','access_time_desc','sign_time','sign_time_desc','investment_area','investment_name','investment_is_listed','investment_is_soe','investment_is_soke','investment_is_global500','investment_is_china500','asset_type'];

        if($this->request->isPost()){
            if(!$this->chargedep_data && !$this->auth->isSuperAdmin())
                $this->error('请先绑定所属街道或部门');
            $file = $this->request->request('filepath');
            $extra_data = ['library_id'=>1,'library_name'=>'在谈库'];
            $this->importExcel($file, DISCUSS);
        }
        $this->view->assign('library_id',DISCUSS);
        // $expurl = url('exptpl', ['library_id'=>DISCUSS]);
        $expurl = '/template/discuss.xlsx';

        $this->assign('expurl', $expurl);
        return $this->view->fetch('import');
    }

    public function importsigned() {

        if($this->request->isPost()){
            if(!$this->chargedep_data && !$this->auth->isSuperAdmin())
                $this->error('请先绑定所属街道或部门');
            $file = $this->request->request('filepath');
            $extra_data = ['library_id'=>SIGNED, 'library_name'=>'签约库'];
            $this->importExcel($file,SIGNED);
        }
        $this->view->assign('library_id',SIGNED);
        // $expurl = url('exptpl', ['library_id'=>SIGNED]);
        $expurl = '/template/signed.xlsx';
        // if($library_id == 1)
        // {
        //     $save_name = '在谈项目库导入模板';
        //     $file_name = ROOT_PATH.'public/template/discuss.xlsx';
        // }
        // if($library_id == 2)
        // {
        //     $save_name = '签约项目库导入模板';
        //     $file_name = ROOT_PATH.'public/template/signed.xlsx';
        // }
        $this->assign('expurl', $expurl);
        return $this->view->fetch('import');
    }
    public function exptpl($library_id = 0){
        $error_msg ='';
        if($library_id == 0)
            $this->error('请选择正确的项目库');
        if($library_id == 1)
        {
            $save_name = '在谈项目库导入模板';
            $file_name = ROOT_PATH.'public/template/discuss.xlsx';
        }
        if($library_id == 2)
        {
            $save_name = '签约项目库导入模板';
            $file_name = ROOT_PATH.'public/template/signed.xlsx';
        }
        $save_name = ieurlencode($save_name);
        if (! file_exists ( $file_name )) {
            header('HTTP/1.1 404 NOT FOUND');
        } else {
            $filesize = filesize($file_name);
            header("Content-type: application/vnd.ms-excel");
            header("Content-Type: application/force-download");
            header('Content-Disposition: attachment;filename="'.$save_name.'.xlsx"');
            header( "Content-Length:   ".$filesize);
            $data = file_get_contents($file_name);
            echo $data;
        }
    }
    public function exportdiscuss(){
        ini_set('memory_limit', '999M');


        $xlsName = $this->exportpre.'在谈库数据导出';
        $groupIds = $this->auth->getGroupIds();
        $this->whereExtend['is_delete'] = 0;
        $this->whereExtend['library_id'] = 1;
        $this->whereExtend['is_visible'] = 1;

        if(/*in_array(GROUP_DISTRICTUNIT,$groupIds) || */in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }
        if(in_array(GROUP_DISTRICTUNIT,$groupIds) )
        {
            // $this->whereExtend['is_add'] = 1;
            // $this->whereExtend['is_visible'] = 1;
        }
        if(in_array(GROUP_BUSINESS,$groupIds) )
        {
            // $this->whereExtend['is_add'] = 1;
            // $this->whereExtend['is_visible'] = 1;
            $this->whereExtend['is_visible_sz'] = 1;
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->count();
        if($total == 0)
            $this->error('暂无数据导出');
        $xlsCell = array('序号','项目名称','提报部门','项目简介','进展情况','存在问题','下步措施','产业类别','项目阶段','总投资','内资金额','外资金额','是否准入','准入时间','签约时间','投资方地区','投资方名称','投资方属性','拟落户街道','项目来源','联系人及联系方式','项目状态','原因');
        $xlsDataReal = [];

        $list = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->where(['suspend_type'=>0])
            ->select();

        foreach ($list as $key => $value) {
            $five_category = $value['five_industry_name'];
            $industry_category_names = '';
            $industry_category_names =str_replace('都不是','',$value['industry_category_names']);
            $industry_category_names =str_replace(',','',$industry_category_names);
            if($industry_category_names)
                $five_category .=''.$industry_category_names;
            if($value['is_access'] == '是')
                $access_time = trim($value['access_time_desc']);
            else
                $access_time = '';

            $xlsDataReal[] = [
                ++$key,
                $value['name'],
                str_replace(',','/',$value['chargedep_names']),
                $value['summary'],
                $value['progression'],
                $value['problem'],
                $value['next_measure'],
                $five_category,
                $value['progress_status_name'],
                formatprice(trim($value['investment_total'])),
                formatprice(trim($value['domestic_capital'])),
                formatprice(trim($value['foreign_capital'])),
                $value['is_access'],
                $access_time,
                $value['sign_time_desc'],
                $value['investment_area'],
                $value['investment_name'],
                str_replace(',','/',trim($value['investment_attribute_names'])),
                $value['planned_street_names'],
                str_replace(',','/',trim($value['project_source_names'])),
                $value['city_district_contact'],
                '',
                ''
            ];

        }

        $list2 = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->where(['suspend_type'=>['>',0]])
            ->select();

        foreach ($list2 as $key => $value) {
            $five_category = $value['five_industry_name'];
            $industry_category_names = '';
            $industry_category_names =str_replace('都不是','',$value['industry_category_names']);
            $industry_category_names =str_replace(',','',$industry_category_names);
            if($industry_category_names)
                $five_category .=''.$industry_category_names;
            if($value['is_access'] == '是')
                $access_time = trim($value['access_time_desc']);
            else
                $access_time = '';

            switch ($value['suspend_type']) {
                case 1:
                    $suspend_type = '终止';
                    $suspend_memo = $value['suspend_memo'];
                    break;
                case 2:
                    $suspend_type = '暂停';
                    $suspend_memo = $value['suspend_memo'];
                    break;
                case 3:
                    $suspend_type = '重复包装';
                    $suspend_memo = $value['suspend_memo'];
                    break;
                default:
                    $suspend_type = '';
                    $suspend_memo = '';
                    break;
            }

            $xlsDataReal[] = [
                ++$key,
                $value['name'],
                str_replace(',','/',$value['chargedep_names']),
                $value['summary'],
                $value['progression'],
                $value['problem'],
                $value['next_measure'],
                $five_category,
                $value['progress_status_name'],
                formatprice(trim($value['investment_total'])),
                formatprice(trim($value['domestic_capital'])),
                formatprice(trim($value['foreign_capital'])),
                $value['is_access'],
                $access_time,
                $value['sign_time_desc'],
                $value['investment_area'],
                $value['investment_name'],
                str_replace(',','/',trim($value['investment_attribute_names'])),
                $value['planned_street_names'],
                str_replace(',','/',trim($value['project_source_names'])),
                $value['city_district_contact'],
                $suspend_type,
                $suspend_memo
            ];

        }
        exportExcel($xlsName,'Excel2007', $xlsDataReal, $xlsCell);
    }
    public function exportsigned()
    {
        ini_set('memory_limit', '999M');

        $groupIds = $this->auth->getGroupIds();

        $this->whereExtend['is_delete'] = 0;
        $this->whereExtend['library_id'] = 2;
        $this->whereExtend['investment_total'] = ['>=',1];
        $this->whereExtend['is_visible'] = 1;
        if(/*in_array(GROUP_DISTRICTUNIT,$groupIds) || */in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }
        if(in_array(GROUP_DISTRICTUNIT,$groupIds) )
        {
            // $this->whereExtend['is_add'] = 1;

        }
        if(in_array(GROUP_BUSINESS,$groupIds) )
        {
            // $this->whereExtend['is_add'] = 1;

            $this->whereExtend['is_visible_sz'] = 1;
        }
        // $filter = $this->request->get("filter", '');
        // $filter = (array)json_decode($filter, true);
        // if(isset($filter['year'])){
        //     $year = $filter['year'];
        //     if($year == 2020)
        //         $this->exportpre = ''
        // }
        $xlsName = $this->exportpre.'签约库数据导出';
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->count();
        if($total == 0)
            $this->error('暂无数据导出');
        $xlsCell = array('序号','项目名称','提报部门','主要内容','产业类别','总投资','内资金额','外资金额','是否准入','准入时间','框架协议时间','正式协议时间','注册时间','是否拿地','拿地时间','开工时间','投资方地区','投资方名称','投资方属性','落户街道','项目来源','联系人及联系方式','项目状态','原因');
        $xlsDataReal = [];
        $list = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->where(['suspend_type'=>0])
            ->select();

        // echo $this->model->getLastSql();

        foreach ($list as $key => $value) {
            $five_category = $value['five_industry_name'];
            $industry_category_names = '';
            $industry_category_names =str_replace('都不是','',$value['industry_category_names']);
            $industry_category_names =str_replace(',','',$industry_category_names);
            if($industry_category_names)
                $five_category .=''.$industry_category_names;
            if($value['is_access'] == '是')
                $access_time = trim($value['access_time_desc']);
            else
                $access_time = '';
            if($value['is_land'] == '是')
            {
                $land_time = $value['land_time_desc'];
                $start_construction_time =  $value['start_construction_time_desc'];
            }
            else{
                $land_time = '';
                $start_construction_time = '';
            }


            $xlsDataReal[] = [
                ++$key,
                $value['name'],
                str_replace(',','/',$value['chargedep_names']),
                $value['summary'],
                $five_category,
                formatprice(trim($value['investment_total'])),
                formatprice(trim($value['domestic_capital'])),
                formatprice(trim($value['foreign_capital'])),
                $value['is_access'],
                $access_time,
                $value['framework_agreement_time_desc'],
                $value['invesment_agreement_time_desc'],
                $value['register_time_desc'],
                $value['is_land'],
                $land_time,
                $start_construction_time,
                $value['investment_area'],
                $value['investment_name'],
                str_replace(',','/',trim($value['investment_attribute_names'])),
                $value['settle_street_names'],
                str_replace(',','/',trim($value['project_source_names'])),
                $value['city_district_contact'],
                '',
                ''
            ];

        }

        $list2 = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->where(['suspend_type'=>['>',0]])
            ->select();

        // echo $this->model->getLastSql();

        foreach ($list2 as $key => $value) {
            $five_category = $value['five_industry_name'];
            $industry_category_names = '';
            $industry_category_names =str_replace('都不是','',$value['industry_category_names']);
            $industry_category_names =str_replace(',','',$industry_category_names);
            if($industry_category_names)
                $five_category .=''.$industry_category_names;
            if($value['is_access'] == '是')
                $access_time = trim($value['access_time_desc']);
            else
                $access_time = '';
            if($value['is_land'] == '是')
            {
                $land_time = $value['land_time_desc'];
                $start_construction_time =  $value['start_construction_time_desc'];
            }
            else{
                $land_time = '';
                $start_construction_time = '';
            }

            switch ($value['suspend_type']) {
                case 1:
                    $suspend_type = '终止';
                    $suspend_memo = $value['suspend_memo'];
                    break;
                case 2:
                    $suspend_type = '暂停';
                    $suspend_memo = $value['suspend_memo'];
                    break;
                case 3:
                    $suspend_type = '重复包装';
                    $suspend_memo = $value['suspend_memo'];
                    break;
                default:
                    $suspend_type = '';
                    $suspend_memo = '';
                    break;
            }


            $xlsDataReal[] = [
                ++$key,
                $value['name'],
                str_replace(',','/',$value['chargedep_names']),
                $value['summary'],
                $five_category,
                formatprice(trim($value['investment_total'])),
                formatprice(trim($value['domestic_capital'])),
                formatprice(trim($value['foreign_capital'])),
                $value['is_access'],
                $access_time,
                $value['framework_agreement_time_desc'],
                $value['invesment_agreement_time_desc'],
                $value['register_time_desc'],
                $value['is_land'],
                $land_time,
                $start_construction_time,
                $value['investment_area'],
                $value['investment_name'],
                str_replace(',','/',trim($value['investment_attribute_names'])),
                $value['settle_street_names'],
                str_replace(',','/',trim($value['project_source_names'])),
                $value['city_district_contact'],
                $suspend_type,
                $suspend_memo
            ];

        }
        // pr($xlsDataReal);
        exportExcel($xlsName,'Excel2007', $xlsDataReal, $xlsCell);

    }


    public function exportnew()
    {
        ini_set('memory_limit', '999M');

        $groupIds = $this->auth->getGroupIds();


        if(/*in_array(GROUP_DISTRICTUNIT,$groupIds) || */in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }
        $xlsName = $this->exportpre.'签约新征地项目数据导出';
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->where(['carrier_id' => 1 , 'is_visible' => 1])
            ->select();
        $xlsCell = array('序号','项目名称','提报部门','主要内容','产业类别','总投资','内资金额','外资金额','是否准入','准入时间','框架协议时间','正式协议时间','注册时间','是否拿地','拿地时间','开工时间','投资方地区','投资方名称','投资方属性','落户街道','项目来源','载体面积','联系人及联系方式');
        $xlsDataReal = [];
        foreach ($list as $key => $value) {
            $five_category = $value['five_industry_name'];
            $industry_category_names = '';
            $industry_category_names =str_replace('都不是','',$value['industry_category_names']);
            $industry_category_names =str_replace(',','',$industry_category_names);
            if($industry_category_names)
                $five_category .=''.$industry_category_names;
            if($value['is_access'] == '是')
                $access_time = trim($value['access_time_desc']);
            else
                $access_time = '';
            if($value['is_land'] == '是')
            {
                $land_time = $value['land_time_desc'];
                $start_construction_time =  $value['start_construction_time_desc'];
            }
            else{
                $land_time = '';
                $start_construction_time = '';
            }
            if(!empty($value['carrier_id_relation']) && $value['carrier_id_relation']!='待定')
                if($value['carrier_id']==1||$value['carrier_id']==6 )
                    $carrier_id_relation = $value['carrier_id_relation'].'亩';
                else if($value['carrier_id']==2 ||$value['carrier_id']==3|| $value['carrier_id']==4){
                    $carrier_id_relation = $value['carrier_id_relation'].'平米';
                }else
                    $carrier_id_relation = $value['carrier_id_relation'];
            else
                $carrier_id_relation = $value['carrier_id_relation'];
            $xlsDataReal[] = [
                ++$key,
                $value['name'],
                str_replace(',','/',$value['chargedep_names']),
                $value['summary'],
                $five_category,
                formatprice(trim($value['investment_total'])),
                formatprice(trim($value['domestic_capital'])),
                formatprice(trim($value['foreign_capital'])),
                $value['is_access'],
                $access_time,
                $value['framework_agreement_time_desc'],
                $value['invesment_agreement_time_desc'],
                $value['register_time_desc'],
                $value['is_land'],
                $land_time,
                $start_construction_time,
                $value['investment_area'],
                $value['investment_name'],
                str_replace(',','/',trim($value['investment_attribute_names'])),
                $value['settle_street_names'],
                str_replace(',','/',trim($value['project_source_names'])),
                $carrier_id_relation,
                $value['city_district_contact']
            ];

        }

        exportExcel($xlsName,'Excel2007', $xlsDataReal, $xlsCell);

    }



    public function exportmajor()
    {
        ini_set('memory_limit', '999M');
        $groupIds = $this->auth->getGroupIds();
        $showAna = true;
        if(/*in_array(GROUP_DISTRICTUNIT,$groupIds) || */in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }
        $xlsName = $this->exportpre.'重点项目库导出';

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $total = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->where(['is_important' => 1 , 'library_id' => SIGNED])
            ->count();
        if($total == 0)
            $this->error('暂无数据导出');

        $list = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->where(['is_important' => 1 , 'library_id' => SIGNED,'year'=>$this->year])
            ->select();


        $xlsCell = array('序号','项目名称','提报部门','主要内容','进展情况','存在问题','下一步措施','产业类别','总投资','内资金额','外资金额','是否准入','准入时间','框架协议时间','正式协议时间','注册时间','是否拿地','拿地时间','开工时间','投资方地区','投资方名称','投资方属性','落户街道','项目来源','载体面积','联系人及联系方式');
        $xlsDataReal = [];
        foreach ($list as $key => $value) {
            $five_category = $value['five_industry_name'];
            $industry_category_names = '';
            $industry_category_names =str_replace('都不是','',$value['industry_category_names']);
            $industry_category_names =str_replace(',','',$industry_category_names);
            if($industry_category_names)
                $five_category .=''.$industry_category_names;
            if($value['is_access'] == '是')
                $access_time = trim($value['access_time_desc']);
            else
                $access_time = '';
            if($value['is_land'] == '是')
            {
                $land_time = $value['land_time_desc'];
                $start_construction_time =  $value['start_construction_time_desc'];
            }
            else{
                $land_time = '';
                $start_construction_time = '';
            }
            if(!empty($value['carrier_id_relation']) && $value['carrier_id_relation']!='待定')
                if($value['carrier_id']==1||$value['carrier_id']==6)
                    $carrier_id_relation = $value['carrier_id_relation'].'亩';
                else if($value['carrier_id']==2 ||$value['carrier_id']==3|| $value['carrier_id']==4){
                    $carrier_id_relation = $value['carrier_id_relation'].'平米';
                }else
                    $carrier_id_relation = $value['carrier_id_relation'];
            else
                $carrier_id_relation = $value['carrier_id_relation'];
            $xlsDataReal[] = [
                ++$key,
                $value['name'],
                str_replace(',','/',$value['chargedep_names']),
                $value['summary'],
                $value['progression'],
                $value['problem'],
                $value['next_measure'],
                $five_category,
                formatprice(trim($value['investment_total'])),
                formatprice(trim($value['domestic_capital'])),
                formatprice(trim($value['foreign_capital'])),
                $value['is_access'],
                $access_time,
                $value['framework_agreement_time_desc'],
                $value['invesment_agreement_time_desc'],
                $value['register_time_desc'],
                $value['is_land'],
                $land_time,
                $start_construction_time,
                $value['investment_area'],
                $value['investment_name'],
                str_replace(',','/',trim($value['investment_attribute_names'])),
                $value['settle_street_names'],
                str_replace(',','/',trim($value['project_source_names'])),
                $carrier_id_relation,
                $value['city_district_contact']
            ];
        }
        exportExcel($xlsName,'Excel2007', $xlsDataReal, $xlsCell);
    }


    protected function __baselist() {
        // pr($where_extend);
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $this->whereExtend['is_delete'] = 0;
            // var_dump($this->whereExtend);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $exp = new \think\db\Expression('field(status,1,0,-1)');
            if(isset($this->whereExtend['library_id']) && $this->whereExtend['library_id'] == SIGNED && !isset($this->whereExtend['is_important']) ){

                $total = $this->model->with($this->relationtTable)
                    ->where($where)
                    // ->where($where_extend)
                    ->where($this->whereExtend)

                    ->where('if(status = -1,1=1,investment_total>0 or tmp_investment_total>0)')
                    // ->order($sort, $order)
                    // ->order('is_add desc')
                    // ->order('is_convert desc')
                    ->order($exp )
                    ->order('id desc')
                    ->count();

                $list = $this->model->with($this->relationtTable)
                    ->where($where)
                    // ->where($where_extend)
                    ->where($this->whereExtend)
                    ->where('if(status = -1,1=1,investment_total>0 or tmp_investment_total>0)')
                    // ->order('is_add desc')
                    // ->order('is_convert desc')
                    ->order($exp )
                    ->order('id desc')
                    // ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
                // echo $this->model->getLastSql();
            }
            else{
                $total = $this->model->with($this->relationtTable)
                    ->where($where)
                    // ->where($where_extend)
                    ->where($this->whereExtend)
                    // ->order('is_add desc')
                    // ->order('is_convert desc')
                    ->order($exp )
                    ->order('id desc')
                    ->count();

                $list = $this->model->with($this->relationtTable)
                    ->where($where)
                    // ->where($where_extend)
                    ->where($this->whereExtend)
                    // ->order('is_add desc')
                    // ->order('is_convert desc')
                    ->order($exp )
                    ->order('id desc')
                    ->limit($offset, $limit)
                    ->select();
            }

            // echo ($this->model->getLastSql());
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            // echo $this->model->getLastSql();
            return json($result);
        }
        return $this->view->fetch();
    }

    protected function addCheckLog($ids,$field='',$data=[]){
        // pr($row->toArray());

        // $table_name = $this->model->getQuery()->getTable();
        // $field_row = Fields::where(['table_name'=>$table_name, 'item_id'=>$field])->order('weight','asc')->find();
        $row = $this->model -> get($ids);
        if(isset($data['desc']))
            $operate_desc = $data['desc'];
        else
        {
            switch ($data['status']) {
                case STATUS_SUBMIT:
                    $operate_desc = '提交';
                    // $operate_info = $row['tmp_'.$field.'_submit_desc'];
                    break;
                case STATUS_PASS:
                    $operate_desc = '审核通过';
                    // $operate_info = '';
                    break;
                case STATUS_REJECT:
                    $operate_desc = '驳回';
                    // $operate_info = $row['tmp_'.$field.'_reject_desc'];
                    break;
                case STATUS_CREATE:
                    $operate_desc = '项目创建';
                    // $operate_info = $row['tmp_'.$field.'_reject_desc'];
                    break;
                default:
                    $operate_desc = '';
                    break;
            }
        }

        $logData = [
            'project_pno' => $row->pno,
            'table_name' => $this->tablename,
            'project_name'  => $row ->name,
            'operator_id'   => $this -> auth -> id,
            'operator_nickname' => $this -> auth -> nickname,
            'operate_desc'  => $operate_desc,
            'operate_field' => $field?$field:(isset($data['field'])?$data['field']:''),
            'operate_field_label' =>isset($data['label'])?$data['label']:'',
            'operate_original_value' => isset($data['original_value'])?$data['original_value']:'',
            'operate_value' => isset($data['value'])?$data['value']:'',
            'operate_info' => isset($data['info'])?$data['info']:'',
            'operate_status' => $data['status'],
        ];
        \app\admin\model\ProjectChecklog::create($logData);
    }

    protected function addCheckLogMulti($ids,$dataAll=[]){
        // pr($dataAll);
        $row = $this->model -> get($ids);
        foreach ($dataAll as $key => $data) {
            if(isset($data['desc']))
                $operate_desc = $data['desc'];
            else
            {
                switch ($data['status']) {
                    case STATUS_SUBMIT:
                        $operate_desc = '提交';
                        // $operate_info = $row['tmp_'.$field.'_submit_desc'];
                        break;
                    case STATUS_PASS:
                        $operate_desc = '审核通过';
                        // $operate_info = '';
                        break;
                    case STATUS_REJECT:
                        $operate_desc = '驳回';
                        // $operate_info = $row['tmp_'.$field.'_reject_desc'];
                        break;
                    case STATUS_CREATE:
                        $operate_desc = '项目创建';
                        // $operate_info = $row['tmp_'.$field.'_reject_desc'];
                        break;
                    default:
                        $operate_desc = '';
                        break;
                }
            }

            $logData = [
                'project_pno' => $row->pno,
                'table_name' => $this->tablename,
                'project_name'  => $row ->name,
                'operator_id'   => $this -> auth -> id,
                'operator_nickname' => $this -> auth -> nickname,
                'operate_desc'  => $operate_desc,
                'operate_field' => $data['field'],
                'operate_field_label' =>isset($data['label'])?$data['label']:'',
                'operate_original_value' => isset($data['original_value'])?$data['original_value']:'',
                'operate_value' => isset($data['value'])?$data['value']:'',
                'operate_info' => isset($data['info'])?$data['info']:'',
                'operate_status' => $data['status'],
            ];
            \app\admin\model\ProjectChecklog::create($logData);
        }

    }

    protected function __add($library_id,$is_important = 0){
        $field_where = $this->fieldWhere($library_id, ACTION_ADD);
        // echo $is_important;
        $fields_list = Fields::where($field_where)->order('weight','asc')->select();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $msg = '提交成功';
            if ($params) {
                $params = $this->preExcludeFields($params);
                $data['pno'] = Random::uuid();
                $data['library_id'] = $library_id;

                $data['name'] = $params['name'];
                $data['is_add'] = 1;
                $data['convert_memo'] = '新增';

                // $data['is_important'] = $is_important;
                $exist_row = $this->model->where(['name'=>$data['name'],'is_delete'=>0])->find();
                if($exist_row)
                    $this->error(__("此项目已存在{$exist_row['library_name']}中"));
                if($library_id  == DISCUSS)
                {
                    $data['library_name'] = '在谈库';

                }
                if($library_id  == SIGNED){
                    $data['library_name'] = '签约库';
                }
                $data['is_visible'] = 0;
                foreach ($fields_list as $key => $value) {
                    if($this->auth->isSuperAdmin())
                    {
                        $field = $value['item_id'];
                        $staus = STATUS_CREATE;
                        $data['status'] = -1;

                    }
                    else{
                        $field = 'tmp_'.$value['item_id'];
                        $staus = STATUS_SUBMIT;
                        $data['chargedep_ids'] = $this->chargedep_data->chargedep_id;
                        $data['chargedep_names'] = $this->chargedep_data->chargedep_name;
                        $data['status'] = 1;
                        // $data['street_status'] = $staus;
                    }
                    if(!isset($params[$field]))
                        continue;


                    if($params[$field] == '待定'){
                        $params[$field] = PENDING;
                    }
                    if($value['item_id'] == 'project_source_ids') {
                        if(is_array($params[$field]) && $params[$field][0])
                        {
                            $is_important = getIsImportant($params[$field]);
                        }
                        $data['is_important'] = $is_important;

                    }

                    // if($value['item_id'] == 'investment_total')
                    // {
                    //     if($params[$field] < 1)
                    //         $msg .= ',此项目转入重大签约项目，请在重大签约项目库中查看';
                    // }
                    if(is_array($params[$field]))
                        $params[$field] = implode(",",$params[$field]);

                    if(isset($params[$field]) && $params[$field])
                    {
                        $data[$field] = $params[$field];
                        if(!$this->auth->isSuperAdmin())
                            $data[$field.'_status'] = STATUS_SUBMIT;

                        if($value['item_type'] == "select" || $value['item_type'] == "selects")
                        {
                            // echo "Aaaa";
                            $rule = json_decode($value['item_rule'], true);
                            $name_field = str_replace('id','name', $field);
                            if(is_string($rule['datasource'])){
                                $tb_name = $rule['datasource'];
                                $data[$name_field] =  getSelectText($tb_name,$params[$field]);
                            }else
                                $data[$name_field] = $rule['datasource'][$params[$field]];


                        }

                        if($value['item_type'] == "datetime" || $value['item_type'] == "date")
                        {
                            if($params[$field] == PENDING)
                                $data[$field.'_desc'] = '待定';
                            else
                                $data[$field.'_desc'] = $params[$field];
                            // $data_params['value'] = $data_params['value'];
                        }

                        if($value['item_id'] == 'carrier_id'){
                            $data[$field.'_relation'] = $params[$field.'_relation'];
                        }
                    }
                }

                // echo $params["{$this->pre}project_socialized"];
                if(isset($params["{$this->pre}project_socialized"]) ) {
                    $data["{$this->pre}project_socialized"] = $params["{$this->pre}project_socialized"];
                    if(!$this->auth->isSuperAdmin())
                        $data["{$this->pre}project_socialized_status"] = STATUS_SUBMIT;
                    if($params["{$this->pre}project_socialized"] == '是'){
                        foreach($this->project_socialized as $key => $value) {
                            if($this->auth->isSuperAdmin())
                            {
                                $field = $value['item_id'];
                            }
                            else{
                                $field = 'tmp_'.$value['item_id'];
                                // $data['street_status'] = $staus;
                            }

                            if(isset($params[$field]) && $params[$field])
                            {
                                $data[$field] = $params[$field];
                                if(!$this->auth->isSuperAdmin())
                                    $data[$field.'_status'] = STATUS_SUBMIT;

                                if($value['item_type'] == "datetime" || $value['item_type'] == "date")
                                {
                                    $data[$field.'_desc'] = $params[$field];
                                }
                            }
                        }
                    }

                }
                // var_dump($data);
                // exit();
                // var_dump($msg);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($data);

                    $projectLogic = \app\admin\logic\Project::instance();
                    $projectLogic->updateDispathPno($data['name'],$data['pno']);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    // $row = $this->model->get($this->model->id);
                    $this->addCheckLog($this->model->id, '', ['status'=>STATUS_CREATE]);

                    $this->success($msg);
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $list = [];
        foreach ($fields_list as $key => $value) {
            if(!$this->auth->isSuperAdmin() && $value['item_id'] == 'chargedep_ids')
                continue;

            $item_required = $value['item_required'] ? json_decode($value['item_required'],true):'';
            // pr($item_required );
            // echo $value['item_label'];
            // echo $value['item_class'];
            $value['item_data_msg'] = '';
            $value['item_required'] = 0;
            $value['item_data_rule'] = '';
            $value['item_pending'] = 0;

            if($item_required && !$this->auth->isSuperAdmin())
            {
                $value['item_pending'] = $item_required[$library_id]['is_pending'];
                // if($this->auth->isSuperAdmin()){
                //     if($value['item_id'] == 'chargedep_ids')
                //     {
                //         $value['item_required'] = 1;
                //         $value['item_data_rule'] = 'data-rule="required"';
                //     }
                // }
                // else{

                    $is_required = $item_required[$library_id]['is_required'];
                    $value['item_required'] = $is_required;
                    $value['item_data_rule'] = $is_required==1?'data-rule="required"':'';

                    if($value['item_class'] == 'capital' && $is_required )
                    {
                        $value['item_data_rule'] = 'data-rule="required(from, .capital);"';
                        $value['item_data_msg'] = 'data-msg-required="内外资至少填一项"';
                    }

                    if($value['item_class'] == 'agreement' && $is_required )
                    {
                        $value['item_data_rule'] = 'data-rule="required(from, .agreement);"';
                        $value['item_data_msg'] = 'data-msg-required="框架与正式协议至少填一项"';
                    }
                // }

            }


            if($value['item_rule'])
                $value['item_rule'] = json_decode($value['item_rule'],true);
            else
                $value['item_rule'] = [];

            $item_rule = $value['item_rule'];

            if($value['item_type'] == 'text')
                $value['item_rule'] = empty($value['item_rule']) ? ['row'=>2]:$value['item_rule'];



            if($value['item_type'] == 'select' || $value['item_type'] == 'selects')
            {
                $options = [];
                if($item_rule)
                {
                    // $item_rule = json_decode($value['item_rule'],true);
                    // pr($item_rule);
                    if(is_string($item_rule['datasource'])){
                        $tablename = $item_rule['datasource'];
                        $option_where = [];
                        if(isset($item_rule['library']))
                            $option_where['library_id'] = $library_id;
                        if(isset($item_rule['group_id']))
                            $option_where['group_id'] = $item_rule['group_id'];
                        if($value['item_id'] == 'project_source_ids' )
                        {
                            if($library_id == DISCUSS)
                                $option_where['library_id'] = 0;
                            $option_where['year'] = ['in',[0,$this->year]];
                        }

                        $options = getSelectList($tablename, $option_where);
                        // $options = getSelectList($tablename);
                    }
                    else
                        $options = $item_rule['datasource'];
                    $item_rule['datasource'] = $options;
                    $value['item_rule'] = $item_rule;
                }
            }
            $value['div_class'] = 'div-'.$value['item_id'];
            if(!$this->auth->isSuperAdmin())
                $value['item_id'] = 'tmp_'.$value['item_id'];

            $list[] = $value;
        }
        $this->view->assign("list", $list);
        $this->view->assign("pre", $this->auth->isSuperAdmin()?"":"tmp_");
        $this->assign("libary_id",$library_id);
        // $this->assign("libary_id",$library_id);
        // pr(collection($list)->toArray());
        return $this->view->fetch('add');
    }


    protected function getRowValue(\app\admin\model\Project $row, \app\admin\model\Fields $field_row,$field) {
        $log_data['original_value'] = $row[$field];
        $log_data['value'] = $row['tmp_'.$field];
        $log_data['label'] = $field_row['item_label'];
        if($field_row['item_type'] == 'select' || $field_row['item_type'] == 'selects')
        {
            $name_field = str_replace('id','name',$field);
            $data[$name_field] = $row['tmp_'.$name_field];
            $data['tmp_'.$name_field] = '';

            $log_data['original_value'] = $row[$name_field];
            $log_data['value'] = $row['tmp_'.$name_field];
        }
        if($field_row['item_type'] == "datetime" ||$field_row['item_type'] == "date")
        {
            $data[$field.'_desc'] = $row['tmp_'.$field.'_desc'];
            $data['tmp_'.$field.'_desc'] = '';

            $log_data['original_value'] = $row[$field.'_desc'];
            $log_data['value'] = $row['tmp_'.$field.'_desc'];

        }
        // if($field_row['item_type'] == 'radio')
        // {
        //     $log_data['original_value'] = $row[$field]? '是':'否';
        //     $log_data['value'] = $row['tmp_'.$field]? '是':'否';
        // }
        return $log_data;
    }


    protected function  fieldWhere($library_id = 0, $action = 0) {
        $where['table_name'] =$this->fields_tablename;
        $where['status'] = 1;
        if($library_id)
            $where['item_library'] = ['in',"0,{$library_id}"];
        if($action)
            $where['item_action'] = ['in',"0,{$action}"];
        if($this->auth->isSuperAdmin())
            $where['item_admin'] = ['in',"0,1"];
        else
            $where['item_admin'] = ['in',"0,2"];

        return $where;
    }

    public function switchyear(){
        if($this -> request -> isAjax()){
            $pno = $this -> request -> post('pno');
            $fromyear = $this -> request -> post('fromyear');
            $toyear = $this -> request -> post('toyear');

            $isExt = \app\admin\model\ProjectYear::get(['pno'=>$pno,'year' => $toyear]);
            $isExtSwitch = \app\admin\model\ProjectYearSwitch::get(['pno'=>$pno,'toyear' => $toyear]);
            if($isExt || $isExtSwitch){
                $this -> error('已经转入');
            }

            $ret = ProjectYearSwitch::create(compact('pno','fromyear','toyear'));
            if($ret){
                $this -> success('记录成功，系统将自动执行转入操作');
            }else{
                $this -> error('失败，请重试');
            }
        }
    }


    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $values = ['is_delete'=>1];
            $count = 0;
            Db::startTrans();
            try {
                $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                foreach ($list as $index => $item) {
                    $count += $item->allowField(true)->isUpdate(true)->save($values);
                }
                // foreach ($list as $k => $v) {
                //     $v->is_delete = 1;

                //     // $count += $v->delete();
                // }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    protected function anaData($where_str = '') {
        $nan = $this -> model -> query("select count(*) as 'projectcount',
sum(case library_id when 2 then 1 else 0 end ) as 'signedcount',
sum(case library_id when 1 then 1 else 0 end ) as 'discusscount',
sum(IF(investment_total > 0,investment_total,0)) as 'investment_total',
SUM(IF(investment_total >= 1,1,0)) as 'over1count',
SUM(IF(investment_total >= 1,investment_total,0)) as 'over1amount',
SUM(IF(investment_total >= 5,1,0)) as 'over5count',
SUM(IF(investment_total >= 5,investment_total,0)) as 'over5amount',
SUM(IF(investment_total >= 50,1,0)) as 'over50count',
SUM(IF(investment_total >= 50,investment_total,0)) as 'over50amount',
SUM(IF(investment_total >= 100,1,0)) as 'over100count',
SUM(IF(investment_total >= 100,investment_total,0)) as 'over100amount',
sum(IF(FIND_IN_SET(1,settle_street_ids),1,0)) as 'chengyangcount',
sum(IF(FIND_IN_SET(1,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'chengyangamount',
sum(IF(FIND_IN_SET(2,settle_street_ids),1,0)) as 'liutingcount',
sum(IF(FIND_IN_SET(2,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'liutingamount',
sum(IF(FIND_IN_SET(3,settle_street_ids),1,0)) as 'xiazhuangcount',
sum(IF(FIND_IN_SET(3,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'xiazhuangamount',
sum(IF(FIND_IN_SET(4,settle_street_ids),1,0)) as 'xifuzhencount',
sum(IF(FIND_IN_SET(4,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'xifuzhenamount',
sum(IF(FIND_IN_SET(5,settle_street_ids),1,0)) as 'jihongtancount',
sum(IF(FIND_IN_SET(5,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'jihongtanamount',
sum(IF(FIND_IN_SET(6,settle_street_ids),1,0)) as 'shangmacount',
sum(IF(FIND_IN_SET(6,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'shangmaamount',
sum(IF(FIND_IN_SET(7,settle_street_ids),1,0)) as 'hetaocount',
sum(IF(FIND_IN_SET(7,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'hetaoamount',
sum(IF(FIND_IN_SET(8,settle_street_ids),1,0)) as 'hongdaocount',
sum(IF(FIND_IN_SET(8,settle_street_ids),investment_total,0)) as 'hongdaoamount',
sum(IF(FIND_IN_SET(13,settle_street_ids),1,0)) as 'guidaocount',
sum(IF(FIND_IN_SET(13,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'guidaoamount',
sum(IF(FIND_IN_SET(14,settle_street_ids),1,0)) as 'jinrongcount',
sum(IF(FIND_IN_SET(14,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'jinrongamount',
sum(IF(FIND_IN_SET(15,settle_street_ids),1,0)) as 'dashujucount',
sum(IF(FIND_IN_SET(15,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'dashujuamount',
sum(IF(FIND_IN_SET(29,settle_street_ids),1,0)) as 'dongchecount',
sum(IF(FIND_IN_SET(29,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'dongcheamount',
sum(IF(FIND_IN_SET(30,settle_street_ids),1,0)) as 'ygctcount',
sum(IF(FIND_IN_SET(30,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'ygctamount',
sum(IF(FIND_IN_SET(41,settle_street_ids),1,0)) as 'rihancount',
sum(IF(FIND_IN_SET(41,settle_street_ids),IF(investment_total > 0,investment_total,0),0)) as 'rihanamount',


sum(case five_industry_id when 1 then 1 else 0 end) as 'gaoduancount',
sum(case five_industry_id when 2 then 1 else 0 end) as 'xinnengyuancount',
sum(case five_industry_id when 3 then 1 else 0 end) as 'xinyidaicount',
sum(case five_industry_id when 4 then 1 else 0 end) as 'shengwucount',
sum(case five_industry_id when 5 then 1 else 0 end) as 'xiandaicount',

sum(IF(FIND_IN_SET(5,industry_category_ids),1,0)) as 'dujiaoshoucount',
sum(IF(FIND_IN_SET(6,industry_category_ids),1,0)) as 'zongbucount',
sum(IF(FIND_IN_SET(7,industry_category_ids),1,0)) as 'zhizhaoyecount',
sum(IF(FIND_IN_SET(8,industry_category_ids),1,0)) as 'xinjijiancount',
sum(IF(FIND_IN_SET(8,industry_category_ids),IF(investment_total > 0,investment_total,0),0)) as 'xinjijianamount',
sum(IF(FIND_IN_SET(9,industry_category_ids),1,0)) as 'gongyecount',
sum(IF(FIND_IN_SET(9,industry_category_ids),IF(investment_total > 0,investment_total,0),0)) as 'gongyeamount',

sum(IF(FIND_IN_SET(3,investment_attribute_ids),1,0)) as 'zhongguo500count',
sum(IF(FIND_IN_SET(4,investment_attribute_ids),1,0)) as 'shijie500count',


sum(IF(framework_agreement_time > 0,IF(invesment_agreement_time ='' or invesment_agreement_time is null or invesment_agreement_time = -100,1,0),0)) as 'kuangjiacount',
sum(IF(invesment_agreement_time > 0 ,1,0)) as 'zhengshicount',
sum(IF(register_time > 0 ,1,0)) as 'zhucecount',
sum(IF(start_construction_time > 0 ,1,0)) as 'kaigongcount',

sum(case is_land='否' when 1 then 1 else 0 end) as 'is_not_land',
sum(case is_land='是' when 1 then 1 else 0 end) as 'is_land',
sum(case land_time>0 and land_time<'".time()."' and is_land='是' when 1 then 1 else 0 end) as 'is_landtime',
sum(IF(land_time<1,is_land='是',0)) as 'is_not_landtime',
sum(IF(register_time>0,is_land='否',0)) as 'is_register',
sum(IF(register_time<1,is_land='否',0)) as 'is_not_register'
from ".$this->project_tablename." where library_id = 2 and investment_total>=1 and  is_delete =0 and suspend_type=0  ".$where_str );
        $nan = $nan[0];

        $str = "
        截至目前，全区签约项目{$nan['signedcount']}个，计划总投资{$nan['investment_total']}亿元。<br />
按投资额划分：过亿元项目{$nan['over1count']}个{$nan['over1amount']}亿元，5亿元以上项目{$nan['over5count']}个{$nan['over5amount']}亿元，50亿元以上项目{$nan['over50count']}个{$nan['over50amount']}亿元，100亿元以上项目{$nan['over100count']}个{$nan['over100amount']}亿元。<br />";
    $str .="按街道划分：";
    if($nan['chengyangcount'] > 0)
        $str .= "城阳街道{$nan['chengyangcount']}个{$nan['chengyangamount']}亿元，";
    if($nan['liutingcount'] > 0)
        $str .= "流亭街道{$nan['liutingcount']}个{$nan['liutingamount']}亿元，";
    if($nan['xiazhuangcount'] > 0)
        $str .= "夏庄街道{$nan['xiazhuangcount']}个{$nan['xiazhuangamount']}亿元，";
    if($nan['jihongtancount'] > 0)
        $str .= "棘洪滩街道{$nan['jihongtancount']}个{$nan['jihongtanamount']}亿元，";
    if($nan['shangmacount'] > 0)
        $str .= "上马街道{$nan['shangmacount']}个{$nan['shangmaamount']}亿元，";
    if($nan['hongdaocount'] > 0)
        $str .= "红岛街道{$nan['hongdaocount']}个{$nan['hongdaoamount']}亿元，";
    if($nan['hetaocount'] > 0)
        $str .= "河套街道{$nan['hetaocount']}个{$nan['hetaoamount']}亿元，";
    if($nan['guidaocount'] > 0)
        $str .= "轨道交通产业示范区{$nan['guidaocount']}个{$nan['guidaoamount']}亿元，";
    if($nan['jinrongcount'] > 0)
        $str .= "区地方金融监督管理局{$nan['jinrongcount']}个{$nan['jinrongamount']}亿元，";
    if($nan['dashujucount'] > 0)
        $str .= "区大数据发展管理局{$nan['dashujucount']}个{$nan['dashujuamount']}亿元，";
    if($nan['dongchecount'] > 0)
        $str .= "动车小镇投资公司{$nan['dongchecount']}个{$nan['dongcheamount']}亿元，";
    if($nan['ygctcount'] > 0)
        $str .= "阳光创新投资有限公司{$nan['ygctcount']}个{$nan['ygctamount']}亿元，";
    if($nan['rihancount'] > 0)
        $str .= "日韩专班{$nan['rihancount']}个{$nan['rihanamount']}亿元，";
    $str .="<br>";
    $str .="按产业划分：高端装备{$nan['gaoduancount']}个，新一代信息技术{$nan['xinyidaicount']}个，新材料新能源{$nan['xinnengyuancount']}个，生物医药{$nan['shengwucount']}个，现代服务业{$nan['xiandaicount']}个。新基建项目{$nan['xinjijiancount']}个{$nan['xinjijianamount']}亿元，工业互联网{$nan['gongyecount']}个{$nan['gongyeamount']}亿元。<br />";
    if($nan['shijie500count']>0)
         $str .="世界500强投资项目{$nan['shijie500count']}个，";
    if($nan['zhongguo500count']>0)
         $str .="中国500强投资项目{$nan['zhongguo500count']}个，";
    if($nan['dujiaoshoucount']>0)
         $str .="独角兽项目{$nan['dujiaoshoucount']}个，";
    if($nan['zongbucount']>0)
         $str .="总部项目{$nan['zongbucount']}个。";
    $str .="<br>";
    $str .="框架协议{$nan['kuangjiacount']}个，正式协议{$nan['zhengshicount']}个；已注册{$nan['zhucecount']}个，已开工{$nan['kaigongcount']}个。<br />
拿地项目{$nan['is_land']}个，非拿地项目{$nan['is_not_land']}个；{$nan['is_land']}个拿地项目中已拿地{$nan['is_landtime']}，未拿地{$nan['is_not_landtime']}个。{$nan['is_not_land']}个非拿地项目中已注册{$nan['is_register']}，未注册{$nan['is_not_register']}个。";

        return $str;
    }



}


